/**
 * 设备工单粗排(批次) V1.00
 */
function cp_man() {
    var id = "cuscomp-" + randNumber();
    lockStore = Ext.create('Ext.data.Store', {
        fields: ['Resource_ID', 'Date', 'Scheduling'],
        data: []
    });
    sourceData();
    /**
     * 统计产线天数
     * */
    function getResDayCount() {
        var day_ary = [], day_cout = [], count = 0;
        var source = theGrid.itemsSource.items;
        foreach(source, function (item) {
            if (day_ary[item.Date] == null) {
                day_ary[item.Date] = item.PlanQty;
                count++;
                day_cout[item.Resource] = count;
            } else {
                day_ary[item.Date] += item.PlanQty;
            }
        });
        return day_cout;
    }
    /**
     * @分组字段 {1} f1 
     * @数据源 {2} list 
     * @查询字段 {3} f2 
     * @返回值字段 {4} f3_name 
     */
    function WijmoGroupDescription(f1, list, f2, f3_name) {
        var gp = new getTop().newObject("wijmo.collections.PropertyGroupDescription", [f1, function (item, propName) {
            var desc = list.filter(function (p) {
                if (p[f2] == item[propName]) {
                    return p;
                }
            });
            return desc.length == 0 ? '' : desc[0][f3_name];
        }]);
        return gp;
    }
    Ext.onReady(function () {
        var group = {
            groupDescriptions: [
                WijmoGroupDescription('ParentID', WorkShopLine, 'Code_ID', 'Description'),
                WijmoGroupDescription('Resource_ID', WorkShopLine, 'Code_ID', 'Description'),
                'Date'
            ],
            sortDescriptions: ['ParentID', 'Resource_index', 'Date', 'S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08', 'S09', 'S10', 'index']
        }

        var columns = [
            { binding: 'index', header: '序号', minWidth: 80, allowSorting: false },
            { binding: 'IsBz', header: '是否标准批', isReadOnly: true, width: 5, visible: true },
            { binding: 'ParentID', header: '车间', width: 130, isReadOnly: true, visible: false, allowDragging: false },
            { binding: 'Resource_ID', header: '设备大类', width: 130, isReadOnly: false, allowDragging: false },
            { binding: 'Resource_index', header: '设备序号', width: 130, visible: false, allowDragging: false },
            { binding: 'Isyc', header: '岩彩/砂壁', width: 130, visible: false },
            { binding: 'Date', header: '日期', name: '排产开始日期', width: 90, dataType: 'Date', format: 'd', allowDragging: false, visible: true, allowSorting: false },
            { binding: 'GcdType', header: '工单类型', isReadOnly: true, width: 5, visible: true, allowSorting: false, allowDragging: false },
            { binding: 'PlanDateStart', header: 't计开', name: '工单开始日期', width: 83, dataType: 'Date', format: 'd', isReadOnly: true, format: 'd', visible: true, allowSorting: false, allowDragging: false },
            { binding: 'ScheduleDateDifference', header: 'ΔT计排', name: '工单开始日期减排产结束日期', width: 75, isReadOnly: true, format: 'd', allowSorting: false, allowDragging: false },
            { binding: 'PlanDateEnd', header: 't计完', name: '工单结束日期', width: 83, dataType: 'Date', format: 'd', isReadOnly: true, format: 'd', visible: true, allowSorting: false, allowDragging: false },		//lab31-210926	
            { binding: 'SaOrderKey', header: '急', width: 50, visible: true },
            { binding: 'CustomerKey', header: '客户类型', width: 50, isReadOnly: true, visible: true, allowSorting: false, allowDragging: false },
            { binding: 'Matching_icon', header: '齐', name: '工单物料是否齐套', width: 50, isReadOnly: true, allowSorting: false },
            { binding: 'IsBeyond', header: '超', width: 50, isReadOnly: true, allowSorting: false, visible: false },
            { binding: 'Matching', width: 30, isReadOnly: true, visible: false, allowSorting: false },
            { binding: 'Lock', header: '锁', name: '工单是否锁定', width: 60 },
            { binding: 'MatchingDate', header: '齐套日期', width: 83, isReadOnly: true },
            { binding: 'Number', header: '工单', width: 106, isReadOnly: false, allowSorting: false, allowDragging: false },
            { binding: 'FStatus', header: '工单状态', width: 65, visible: false, isReadOnly: true, allowSorting: false, allowDragging: false },
            { binding: 'Inventory_ID', header: '物料编码', width: 110, isReadOnly: false, allowSorting: false, allowDragging: false },
            { binding: 'Description', header: '物料名称', width: 180, isReadOnly: true, allowSorting: false, allowDragging: false },
            { binding: 'BatchNO', header: '批次号', width: 101, isReadOnly: false, allowSorting: false, allowDragging: false },
            { binding: 'PlanNpkg', header: '目标数量', width: 100, dataType: 'Number', isReadOnly: true, allowSorting: false, allowDragging: false },
            { binding: 'StdInventory_ID', header: '半成品编码', width: 110, isReadOnly: false, visible: false, allowSorting: false, allowDragging: false },
            { binding: 'Unit_Weight', header: '规格', width: 65, isReadOnly: true, allowSorting: false, allowDragging: false },
            { binding: 'BzNbatch', header: '标准批数', width: 100, dataType: 'Number', aggregate: 'Sum', isReadOnly: true, allowSorting: false, allowDragging: false },
            { binding: 'Nbatch', header: '粗排批数', width: 100, dataType: 'Number', aggregate: 'Sum', isReadOnly: true, allowSorting: false, allowDragging: false },
            { binding: 'PlanQty', header: '计划产量', width: 100, dataType: 'Number', aggregate: 'Sum', isReadOnly: true, allowSorting: false, allowDragging: false },
            { binding: 'PlanDate', header: '∑T排', name: '工时合计', width: 65, dataType: 'Number', aggregate: 'Sum', isReadOnly: true, allowSorting: false, allowDragging: false },
            { binding: 'KDAUF', header: '销售订单号', width: 112, isReadOnly: true, allowSorting: false },	                        //lab31211007		
            { binding: 'KDPOS', header: '销售订单行项目', width: 112, isReadOnly: true, allowSorting: false },
            { binding: 'LvWanAct', header: '半成品工单号', width: 112, isReadOnly: true, allowSorting: false, visible: false },
            { binding: '日占有率', header: '日占有率', width: 100, isReadOnly: true, dataType: 'Number', aggregate: 'Sum', allowSorting: false, allowDragging: false, visible: false },
            { binding: 'Summary', header: '备注', width: 110, isReadOnly: false, allowSorting: false, allowDragging: false },
            { binding: 'HCapacity', header: '小时产能', width: 100, isReadOnly: true, dataType: 'Number', allowSorting: false, allowDragging: false, visible: false },
            { binding: '批占有率', header: '批占有率', width: 100, isReadOnly: true, dataType: 'Number', allowSorting: false, allowDragging: false, visible: false },
            { binding: 'PlanDate', header: 'T计', width: 60, dataType: 'Number', isReadOnly: true, visible: true, allowSorting: false, allowDragging: false, visible: false },
            { binding: 'ScheduleStartDate', header: 't排开', name: '排产开始日期', width: 83, dataType: 'Date', format: 'd', isReadOnly: false, format: 'd', allowSorting: false, allowDragging: false, visible: false },
            { binding: 'ScheduleEndDate', header: 't排完', name: '排产完成日期', width: 79, isReadOnly: true, dataType: 'Date', format: 'd', allowSorting: false, allowDragging: false },
            //{ binding: 'PlanDateEnd', header: 't计完', width: 83, dataType: 'Date', format: 'd', isReadOnly: true, format: 'd', visible: true, allowSorting: false, allowDragging: false },
            { binding: '日产能 ', header: '日产能', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false, visible: false },
            { binding: 'S01', header: 'S1', width: 76, isReadOnly: true, visible: false },
            { binding: 'S02', header: 'S2', width: 76, isReadOnly: true, visible: false },
            { binding: 'S03', header: 'S3', width: 76, isReadOnly: true, visible: false },
            { binding: 'S04', header: 'S4', width: 76, isReadOnly: true, visible: false },
            { binding: 'S05', header: 'S5', width: 76, isReadOnly: true, visible: false },
            { binding: 'S06', header: 'S6', width: 76, isReadOnly: true, visible: false },
            { binding: 'S07', header: 'S7', width: 85, isReadOnly: true, visible: false },
            { binding: 'S08', header: 'S8', width: 85, isReadOnly: true, visible: false },
            { binding: 'S09', header: 'S9', width: 85, isReadOnly: true, visible: false },
            { binding: 'S10', header: 'S10', width: 85, isReadOnly: true, visible: false },
            { binding: 'S11', header: 'S11', width: 85, isReadOnly: true, visible: false },
            { binding: 'S12', header: 'S12', width: 85, isReadOnly: true, visible: false },
            { binding: 'S13', header: 'S13', width: 85, isReadOnly: true, visible: false },
            { binding: 'S14', header: 'S14', width: 85, isReadOnly: true, visible: false },
            { binding: 'S15', header: 'S15', width: 85, isReadOnly: true, visible: false },
            { binding: 'S16', header: 'S16', width: 85, isReadOnly: true, visible: false },
            { binding: 'S17', header: 'S17', width: 85, isReadOnly: true, visible: false },
            { binding: 'S18', header: 'S18', width: 85, isReadOnly: true, visible: false },
            { binding: 'S19', header: 'S19', width: 85, isReadOnly: true, visible: false },
            { binding: 'S20', header: 'S20', width: 85, isReadOnly: true, visible: false },
            { binding: 'OnePlanMAX', header: '批产能', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false, visible: false },
            { binding: '实际日占有率', header: '实际日占有率', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false, visible: false },
            { binding: '实际批占有率', header: '实际批占有率', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false, visible: false },
            { binding: 'ActDateStart ', header: 't实开', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false, visible: false },
            { binding: 'ActDateEnd', header: 't实完', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false, visible: false },
            { binding: 'ActDate', header: 'T实', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false, visible: false },
            { binding: 'T计实差', header: 'ΔT计实', width: 90, isReadOnly: true, allowSorting: false, allowDragging: false, visible: false },
            { binding: 'T排实', header: 'ΔT排实', width: 90, isReadOnly: true, format: 'd', allowSorting: false, allowDragging: false, visible: false },
            { binding: '物料分类', header: '物料分类', isReadOnly: true, width: 90, allowSorting: false, allowDragging: false, visible: false },
            { binding: 'apsno', header: '流水号', isReadOnly: true, width: 90, allowSorting: false, allowDragging: false, visible: false },
            { binding: 'LimitStart', header: '限制开始', isReadOnly: true, width: 90, allowSorting: false, allowDragging: false, visible: false },
            { binding: 'LimitFinish', header: '限制完成', isReadOnly: true, width: 90, allowSorting: false, allowDragging: false, visible: false },
            { binding: 'LimitDifference', header: '生产窗口', isReadOnly: true, width: 90, allowSorting: false, allowDragging: false, visible: false },
        ];
        var comp = Ext.get(id);
        var dom = comp.el.dom;

        var groupcolmn = getTop().newObject("wijmo.collections.CollectionView", [[], {
            groupDescriptions: group.groupDescriptions,
            sortDescriptions: group.sortDescriptions,
        }]);

        var wijmoTooltip = getTop().wijmo.Tooltip;
        let hdrTips = new wijmoTooltip({
            position: 6,
            showAtMouse: true,
            showDelay: 600,
            cssClass: 'hdr-tip'
        });
        let beginEditData = {};
        //创建flexgrid表格对象
        theGrid = new getTop().newObject("wijmo.grid.FlexGrid", [dom, {
            showSort: true,
            allowSorting: false,
            allowMerging: 'ColumnHeaders',
            autoGenerateColumns: false,
            headersVisibility: 'Column',
            selectionMode: 'Row',
            frozenColumns: 7,
            itemsSource: groupcolmn,
            columns: columns,
            loadingRows: function () {
                hdrTips.dispose();
            },
            beginningEdit: function (s, e) {
                var item = s.rows[e.row].dataItem;
                let col = s.columns[e.col];
                if (item.GcdType == 4) {
                    e.cancel = true;
                }
                beginEditData = JSON.parse(JSON.stringify(item));
            },
            rowEditEnded: function (s, e) {
            },
            cellEditEnding: function (s, e) {
                var col = s.columns[e.col];
                if (col.binding == 'Date') {
                    if (s.activeEditor.value != theGrid.getCellData(e.row, e.col)) {
                        theGrid.setCellData(e.row, "ScheduleStartDate", s.activeEditor.value);
                        theGrid.setCellData(e.row, "ScheduleEndDate", s.activeEditor.value);
                    }
                }
                if (col.binding == 'Resource') {
                    if (s.activeEditor.value != theGrid.getCellData(e.row, e.col)) {
                        theGrid.setCellData(e.row, "Resource_ID", s.activeEditor.value);
                    }
                }
            },
            cellEditEnded: function (s, e) {
                let col = s.columns[e.col];
                let source = theGrid.getSourceData();
                let view = theGrid.collectionView;
                let cv = theGrid.itemsSource;
                let rowData = s.selectedItems.length > 0 ? s.selectedItems[0] : null;
                let rowIndex = SpRows(source, rowData.Date, rowData.Resource_ID);
                let _elment = source[rowIndex];
                if (col.binding == 'Date') {
                    if (_elment) {
                        if (new Date(rowData.Date) - new Date(beginEditData.Date) != 0) {
                            theGrid.beginUpdate();
                            for (var key in rowData) {
                                if (key != 'index') {
                                    _elment[key] = rowData[key];
                                }
                            }
                            view.refresh();
                            theGrid.endUpdate();
                            cv.remove(rowData);
                            cv.refresh();
                        }
                    }
                    theGrid.beginUpdate();
                    let n = SpRows(theGrid.itemsSource.items, beginEditData[col.binding], beginEditData['Resource_ID']);
                    if (IsNumber(n)) {
                        let elment = theGrid.itemsSource.items[n];
                        elment.IsBz = 1;
                        elment.BzNbatch = 1;
                    }
                    view.refresh();
                    theGrid.endUpdate();
                    let wk_arry = WorkShopLine.find( x => x.Code_ID == beginEditData['Resource_ID']);
                    let source = theGrid.itemsSource.items.filter(function (p) {
                        let p_date = new Date(p.Date);
                        let m_date = new Date(beginEditData[col.binding]);
                        if (p_date - m_date == 0 && p.Resource_ID == beginEditData['Resource_ID'] && p.BzNbatch == 1) { return p; }
                    });
                    for (let index = 0; index < (wk_arry.Nbatch - source.length); index++) {
                        addSpRows(beginEditData, theGrid.collectionView);
                        theGrid.itemsSource.refresh();
                    }
                }
                if (col.binding == 'Resource') {
                    if (_elment) {
                        if (rowData.Resource_ID != beginEditData.Resource_ID) {
                            theGrid.beginUpdate();
                            for (var key in rowData) {
                                if (key != 'index') {
                                    _elment[key] = rowData[key];
                                }
                            }
                            view.refresh();
                            theGrid.endUpdate();

                            cv.remove(rowData);
                            cv.refresh();
                        }
                    }
                }
                beginEditData = {};
                theGrid.itemsSource.refresh();
            },
            refreshed: function () {
                let source = theGrid.itemsSource.items;
                let ary = [];
                let count = 0;
                for (let i = 0; i < source.length; i++) {
                    const element = source[i];
                    source[i].index = i;
                    if (ary[element.Resource] == null) {
                        ary[element.Resource] = count;
                        count++;
                    }
                    getTop().ResourceIndex.sort(function (a, b) { return a.Index - b.Index });
                    foreach(getTop().ResourceIndex, function (el) {
                        if (el.Resource_ID == source[i].Resource_ID) {
                            source[i].Resource_index = el.Index;
                        }
                    });
                }
            },
            refreshing: function (e) {
                let source = e.itemsSource.items;
                let ccArry = {};
                for (let i = 0; i < source.length; i++) {
                    const element = source[i];
                    if (ccArry[element.Resource_ID + element.Date] == null) {
                        ccArry[element.Resource_ID + element.Date] = 1;
                    } else {
                        ccArry[element.Resource_ID + element.Date] += 1;
                    }
                    let wk_arry = WorkShopLine.find(x => x.Code_ID == element['Resource_ID']);
                    if (wk_arry) {
                        if (wk_arry.Nbatch < ccArry[element.Resource_ID + element.Date]) {
                            source[i].BzNbatch = 0;
                            source[i].IsBz = 0;
                        } else {
                            source[i].BzNbatch = 1;
                            source[i].IsBz = 1;
                        }
                    } else {
                        source[i].BzNbatch = 0;
                        source[i].IsBz = 0;
                    }
                }
            },
            updatedView: function () {
                btnMoveUpward.enable();
                btnMoveDown.enable();
            }
        }]);

        //启用列筛选过滤功能
        var filter = new getTop().newObject("wijmo.grid.filter.FlexGridFilter", [theGrid]);
        filter.defaultFilterType = getTop().wijmo.grid.filter.FilterType.Condition;
        filter.showSortButtons = false;
        //设置分组收缩级别
        theGrid.collapseGroupsToLevel(2);
        //启用wijmo表的列排序功能
        theGrid.sortingColumn.addHandler(function (s, e) {
            var view = s.collectionView, sds = view.sortDescriptions;
            e.cancel = true;
            if (e.data.ctrlKey) {
                sds.clear();
                return;
            }
            var prop = s.columns[e.col].binding, index = -1;
            for (var i = 0; i < sds.length && index < 0; i++) {
                if (sds[i].property == prop) {
                    index = i;
                }393492
            }
            if (index < 0) { // not found, add now
                var sd = new getTop().wijmo.collections.SortDescription(prop, true);
                sds.push(sd);
            }
            else { // found, flip its direction
                var sd = new getTop().wijmo.collections.SortDescription(prop, !sds[index].ascending);
                sds.splice(index, 1, sd);
            }
        });

        //格式化wijmo表格列数据
        theGrid.formatItem.addHandler(function (s, e) {
            if (e.panel == s.columnHeaders) {
                var msg = e.getColumn().name;
                if (!msg) {
                    msg = e.getColumn().header;
                }
                hdrTips.setTooltip(e.cell, '<span>' + msg + '</span>');
            }
            if (e.panel == s.cells) {
                var col = s.columns[e.col];
                var group_level = e._p.rows[e.row].level;
                var val = s.getCellData(e.row, theGrid.getColumn(col.binding).index);
                var html = '<div style="color:{cls}"><span style="font-size:100%">{val}</span> ';
                if (group_level == 1) {
                    var curFlexGridRow = theGrid.rows[e.row];
                    curFlexGridRow.cssClass = 'cell-resource';
                }
                if (col.binding == 'GcdType') {
                    if (group_level == undefined) {
                        if (val == 2) {
                            var curFlexGridRow = theGrid.rows[e.row];
                            curFlexGridRow.cssClass = 'cell-country';
                        }
                    }
                }
                if (col.binding == 'PlanDate') {
                    html = html.replace('{val}', val == undefined ? 0 : val.toFixed(2));
                    if (group_level == 2) {
                        if (val > 11) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                    if (group_level == 1) {
                        if (val > 22) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                    if (group_level == 0) {
                        if (val > 22) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                }
                if (col.binding == 'PlanQty') {
                    var Resource_ID;
                    var day_vount = getResDayCount()[e._p.rows[e.row].dataItem.name];
                    if (group_level == 1 || group_level == 2) {
                        Resource_ID = e._p.rows[e.row].dataItem.items[0].Resource_ID;
                    }
                    if (group_level == 3) {
                        Resource_ID = e._p.rows[e.row].dataItem.items[0].Resource_ID;
                    }
                    var daycn = WorkShopLine.filter(function (p) {
                        if (p.WorkShopId == Resource_ID) {
                            return p;
                        }
                    });
                    var cxn = daycn.length == 0 ? 0.001 : daycn[0].DayProductionCapacity;
                    html = html.replace('{val}', val == undefined ? 0 : val.toFixed(2));
                    if (group_level == 3) {
                        if (val > (cxn / 2)) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                    if (group_level == 2) {
                        if (val > cxn) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                    if (group_level == 1) {
                        if (val > (cxn * day_vount)) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                    if (group_level == 0) {
                        if (val > (cxn * day_vount)) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                }
                if (col.binding == 'IsBz') {
                    html = html.replace('{val}', val == undefined ? 0 : val.toFixed(2));
                    if (group_level == undefined) {
                        if (val == 0) {
                            let curFlexGridRow = theGrid.rows[e.row];
                            curFlexGridRow.cssClass = 'cell-baochan';
                        }
                    }
                }
                if (col.binding == 'Nbatch') {
                    let Resource_ID;
                    if (group_level) {
                        Resource_ID = e._p.rows[e.row].dataItem.items[0].Resource_ID;
                    }
                    var day_vount = getResDayCount()[e._p.rows[e.row].dataItem.name];
                    var daycn = WorkShopLine.filter(function (p) {
                        if (p.Code_ID == Resource_ID) {
                            return p;
                        }
                    });
                    var pishu = daycn.length == 0 ? 0.001 : daycn[0].Nbatch;
                    html = html.replace('{val}', val == undefined ? 0 : val.toFixed(2));
                    if (group_level == 3) {
                        console.log(e._p.rows[e.row]);
                    }
                    if (group_level == 3) {
                        if (val > pishu) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                }
                if (col.binding == 'IsBeyond') {
                    let html = '<div style="color:{cls}"><span style="font-size:100%">&nbsp<i class="fa fa-star" style="padding:0px 3px 5px 10px"></i></span> ';
                    if (val) {
                        html = html.replace('{cls}', 'green');
                        e.cell.innerHTML = html;
                    } else {
                        html = html.replace('{cls}', 'red');
                        e.cell.innerHTML = html;
                    }
                }
                if (col.binding == 'Lock') {
                    let html = '<div style="color:{cls}"><span style="font-size:100%">&nbsp<i class="fa fa-{gly}" style="padding:0px 3px 5px 16px"></i></span> ';
                    if (val == 1) {
                        html = html.replace('{cls}', 'red');
                        html = html.replace('{gly}', 'lock');
                    } else {
                        html = html.replace('{cls}', 'green');
                        html = html.replace('{gly}', 'lock-open');
                    }
                }
                if (col.binding == 'Matching_icon') {
                    val = s.getCellData(e.row, theGrid.getColumn('Matching').index);
                    let html = '<div style="color:{cls}"><span style="font-size:100%">&nbsp<i class="fa fa-circle" style="padding:0px 3px 5px 1px"></i></span> ';
                    switch (val) {
                        case 1:
                            html = html.replace('{cls}', 'green');
                            break;
                        case 0:
                            html = html.replace('{cls}', 'red');
                            break;
                        case 2:
                            html = html.replace('{cls}', 'orange');
                            break;
                        case 3:
                            html = html.replace('{cls}', 'dimgray');
                            break;
                        default:
                            html = html.replace('{cls}', 'dimgray');
                            break;
                    }
                    e.cell.innerHTML = html;
                }
                if (col.binding == 'SaOrderKey') {
                    if (val == 8) {
                        html = html.replace('{cls}', 'red');
                        html = html.replace('{val}', '急');
                    }
                    if (val == 0) {
                        html = html.replace('{cls}', 'greed');
                        html = html.replace('{val}', '');
                    }
                }
                if (col.binding == '日占有率') {
                    var day_vount = getResDayCount()[e._p.rows[e.row].dataItem.name];
                    var Resource_ID;
                    if (group_level == 1 || group_level == 2) {
                        Resource_ID = e._p.rows[e.row].dataItem.items[0].Resource_ID;
                    }
                    var daycn = WorkShopLine.filter(function (p) {
                        if (p.WorkShopId == Resource_ID) {
                            return p;
                        }
                    });
                    var cxn = daycn.length == 0 ? 0.001 : daycn[0].DayProductionCapacity;
                    let html = '<div style="color:{cls}"><span style="font-size:100%">{val}%</span> ';
                    if (group_level == 0) {
                        html = html.replace('{val}', '');
                    } else if (group_level == 1) {
                        if (val && cxn) {
                            html = html.replace('{val}', parseInt(((val) / cxn) * 100 / day_vount));
                        } else {
                            html = html.replace('{val}', '');
                        }
                    } else if (group_level == 2) {
                        if (val && cxn) {
                            html = html.replace('{val}', parseInt(((val) / cxn) * 100));
                        } else {
                            html = html.replace('{val}', '');
                        }
                    } else {
                        html = html.replace('{val}', '');
                    }
                    e.cell.innerHTML = html;
                }
                if (col.binding == '批占有率') {
                    let html = '<div style="color:{cls}"><span style="font-size:100%">{val}%</span> ';
                    if (group_level == 0) {
                        html = html.replace('{val}', '');
                    } else if (group_level == 1) {
                        html = html.replace('{val}', '');
                    } else if (group_level == 2) {
                        html = html.replace('{val}', '');
                    } else if (group_level == 3) {
                        html = html.replace('{val}', '');
                    } else {
                        var invid = s.getCellData(e.row, theGrid.getColumn("Inventory_ID").index);
                        var allsettings = AllSettings.find(x => x.Inventory_ID === invid);
                        var OnePlanMAX = allsettings ? allsettings.OnePlanMAX : 1;
                        if (OnePlanMAX && val) {
                            html = html.replace('{val}', parseInt((val / OnePlanMAX) * 100));
                        } else {
                            html = html.replace('{val}', 0);
                        }
                    }
                    e.cell.innerHTML = html;
                }
                if (col.binding == 'ScheduleDateDifference') {
                    var start = s.getCellData(e.row, theGrid.getColumn("PlanDateStart").index);
                    var temp2 = s.getCellData(e.row, theGrid.getColumn("ScheduleEndDate").index);
                    html = html.replace('{val}', Math.round((new Date(start) - new Date(temp2)) / 1000 / 60 / 60 / 24));
                    e.cell.innerHTML = html;
                }
            }
        });
        theGrid.getSourceData = function () {
            return theGrid.itemsSource.items;
        }
        theGrid.getSelectItem = function () {
            return theGrid.itemsSource.currentItem;
        }
        theGrid.ExportExcel = function (fileName) {
            getTop().wijmo.grid.xlsx.FlexGridXlsxConverter.saveAsync(this, { includeColumnHeaders: true }, fileName + '.xlsx');
        }

        /**
        * 表格列合并
        * colSpan：需要合并的列数据
        * title：合并列标题
        **/
        theGrid.flexGridColSpan = function (colSpan, title) {
            var extraRow = getTop().newObject("wijmo.grid.Row", []);
            extraRow.allowMerging = true;
            var panel = this.columnHeaders;
            panel.rows.splice(0, 0, extraRow);
            colSpan.forEach((header) => {
                panel.setCellData(0, this.getColumn(header).index, title);
            })
            panel.columns.forEach((binding) => {
                if (colSpan.indexOf(binding.binding) == -1) {
                    let col = this.getColumn(binding);
                    col.allowMerging = true;
                    panel.setCellData(0, col.index, col.header);
                }
            });
        }
        /**
         * 字段加载下拉数据
         **/
        theGrid.CreateDataMap = function (ary, column) {
            let ActionsMap = getTop().newObject("wijmo.grid.DataMap", [ary, "id", "name"]);
            theGrid.columns.getColumn(column).dataMap = ActionsMap;
        }

        //列合并
        let colSpan = ["S01", "S02", "S03", "S04", "S05", "S06", "S07", "S08", "S09", "S10", "S11", "S12", "S13", "S14", "S15", "S16", "S17", "S17", "S19", "S20"];
        theGrid.flexGridColSpan(colSpan, "顺位");

        theGrid.RefreshColumnDataMap = function (WorkShopLineMapData) {
            //添加是否急单列下拉数据
            theGrid.CreateDataMap([{ id: 8, name: '急' }, { id: 0, name: '否' }], "SaOrderKey");
            //添加是否锁定下拉数据
            theGrid.CreateDataMap([{ id: 1, name: '已锁' }, { id: 0, name: '未锁' }], "Lock");
            //工单类型
            theGrid.CreateDataMap([{ id: -1, name: '初始化数据' }, { id: 0, name: '产品工单' }, { id: 2, name: '洗机分析' }, { id: 3, name: '洗机工单' }, { id: 4, name: '虚拟工单' }], "GcdType");
            //设备大类下拉数据
            let wk = [];

            foreach(WorkShopLineMapData, (el) => {
                    wk.push({
                        id: el.Code_ID,
                        name: el.Description
                    });
            });
            theGrid.CreateDataMap(wk, "Resource_ID");
        }
        theGrid.RefreshColumnDataMap();
    });

    /**
     * 查看全览表
     * 打开全览表数据
     * */
    let btnViewOverview = Ext.create('Ext.Button', {
        tooltip: '查看全览表',
        glyph: 0xf15c,
        hidden: true,
        handler: function () {
            let cv = theGrid.itemsSource;
            let invid;
            if (cv.currentItem == null || cv.currentItem == '' || cv.currentItem == undefined) {
                Alert('提示：', '请选择需要查询的物料！');
                return false;
            } else {
                invid = cv.currentItem.Inventory_ID
                getTopWindow().openWindow("全览表", "/AllSettings?disble_operate_type=Add,Edit,Delete,Print,Record,BackRecord,Verify&Inventory_ID=" + invid, 1100, 600, function () { });
            }
        }
    });
    var tool = [
        btnReadOldPlan, btnReadNowPlan, btnNotFinishProductionOrder, btnBundleAnalysis, btnViewGdItemShortage, btnViewGdListShortage,
        btnAutomaticSorting, btnOptimizedConfiguration, btnMoveUpward, btnMoveDown, btnVirtualDragSheet,/* btnBeyondAnalysis,*/  btnSave,
        btnVirtualTicketEdit, btnVirtualTicketRead, btnCompleteDateSorting, , btnExpansion, btnShrink, '->', btnLockTicket, btnViewOverview, btnExportExcel, btnDelete, btnInitializationData,
        btnRefreshData
    ];
    return {
        xtype: 'panel',
        layout: 'border',
        tbar: tool,
        items: [
            {
                region: 'center',
                xtype: 'component',
                height: '100%',
                id: id,
                border: false,
                title: false,
                onRender: function () {
                },
                afterRender: function () {
                }
            }
        ]
    };
}
/*
* @FactoryCalendar    加载工厂日历数据
* @Work_Shift   加载班制表数据
* @BS_Work_Shift_Effective_Time  加载班制明细表数据
* @LocaltblItem  加载班次数据
* @AllSettings  加载全览表数据
* @WorkShopLine 加载车间档案数据
* @Gcd_List  加载工单列表数据
*/
function sourceData() {
    //Work_Shift = getListWithMultParams("Work_Shift", { Work_Noid: '' });
    //BS_Work_Shift_Effective_Time = getListWithMultParams("BS_Work_Shift_Effective_Time", { Work_Noid: '' });
    LocaltblItem = getListWithMultParams("LocaltblItem", { Ftype: 'Work_Classes' });
    AllSettings = getListWithMultParams("Inventory", { iii: '' });
    WorkShopLine = getListWithMultParams("WorkShopLine", { WorkShopId: '' });
}

function FlexGridInsert(obj) {
    let view = theGrid.collectionView;
    let data = view.sourceCollection;
    data.push(obj);
    view.refresh();
}
//插入空白行
function addSpRows(element, view) {
    view = theGrid.itemsSource;
    let newItem = {};
    //theGrid.collectionView.addNew();
    // if(!newItem){
    //     view = theGrid.itemsSource;
    //     newItem = view.addNew();
    // }
    if (element) {
        newItem['ParentID'] = element.ParentID;
        newItem.GcdType = -1;
        newItem.IsBz = 1;
        newItem.BzNbatch = 1;
        newItem.Date = getTop().wijmo.Globalize.parseDate(new Date(element.Date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
        newItem.Resource_index = element.Resource_index;
        newItem.Resource_ID = element.Resource_ID;
        newItem.Number = '';
        newItem.Inventory_ID = '';
        newItem.Description = '';
        newItem.BatchNO = '';
        newItem.PlanQty = 0;
        newItem.Nbatch = 1;
        newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(new Date(element.Date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
        newItem.PlanDate = 0;
        newItem.MfgCatID = '';
        newItem.SandTypeId = '';
        newItem.SaOrderKey = 0;
        newItem.FStatus = '';
        newItem.Lock = 0;
        newItem.Capacity = 0;
        newItem.OnePlanMAX = '';
        newItem.StdInventory_ID = '';
        newItem.PlanDateEnd = '';
        newItem.Matching = '';
        newItem.Style = '';
        newItem.Capacity = 0;
        newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(new Date(element.Date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
        newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(new Date(element.Date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
        FlexGridInsert(newItem)
        //view.commitNew();
    }
}
//根据日期、设备大类返回占位行的index
function SpRows(source, date, Resource_ID) {
    let result = null;
    for (let index = 0; index < source.length; index++) {
        const element = source[index];
        let p_date = new Date(element.Date);
        let m_date = new Date(date);
        if (p_date - m_date == 0 && element.Resource_ID == Resource_ID) {
            if (!element.Number) {
                result = index;
                break;
            }
        }
    }
    return result;
}

function NoSpRows(source, date, Resource_ID, Number) {
    let result;
    for (let index = 0; index < source.length; index++) {
        const element = source[index];
        let p_date = new Date(element.Date);
        let m_date = new Date(date);
        if (p_date - m_date == 0 && element.Resource_ID == Resource_ID) {
            if (element.Number == Number) {
                result = source[index];
                break;
            }
        }
    }
    return result;
}
/**
 * 锁定工单
*/
function LockGcd(source) {
    let temp = [];
    let flg = false;
    foreach(lockStore.getData().items, function (el) {
        let item = el.data;
        if (item.Resource_ID == "" || item.Date == "") {
            let row = item.id;
            var j = row.substring(row.indexOf('-') + 1, row.length);
            Alert('提示：', "第" + j + "行有空数据");
        } else {
            let filter = {
                Resource_ID: [item.Resource_ID],
                Date: [item.Date]
            }
            let _row = filterData(temp, filter);
            if (_row.length > 0) {
                Alert('提示：', "不能有重复数据");
            } else {
                temp.push({
                    Resource_ID: item.Resource_ID,
                    Date: item.Date
                });
                foreach(source, function (el) {
                    var d = new Date(el.Date).format('yyyy/MM/dd');
                    if (el.Resource_ID == item.Resource_ID && d == item.Date.format('yyyy/MM/dd')) {
                        el.Lock = item.Lock;
                        flg = true;
                    }
                });
            }
        }
    });
    theGrid.collectionView.refresh();
    return flg;
}
function nSelect(a, b) {//a?对比源??b对比对象[[值，符号，原字段]]??多参数对比
    var tj = ''
    for (let n = 0; n < b.length; n++) {
        let bb = b[n]
        if (n == b.length - 1) {
            tj += `${bb[0]}${bb[1]}ii['${bb[2]}']`
            break;
        }
        tj += `${bb[0]}${bb[1]}ii['${bb[2]}'] &&`;
    }
    for (let i = 0; i < a.length; i++) {
        let ii = a[i];
        if (eval(tj)) {
            return ii
        }
    }
}

function IsNumber(val) {
    if (parseFloat(val).toString() == "NaN") {
        return false;
    } else {
        return true;
    }
}

//自动产生排产数据的占位行
function AssessAddSpRows(source) {
    theGrid.refresh();
    let ccArry = {};
    for (let index = 0; index < source.length; index++) {
        const element = source[index];
        if (element) {
            if (ccArry[element.Resource_ID + element.ScheduleEndDate] == null) {
                ccArry[element.Resource_ID + element.ScheduleEndDate] = 1;
                let temp = WorkShopLine.filter(function (p) {
                    if (element.Resource_ID == p.Code_ID) {
                        return p;
                    }
                });
                let __el = temp[0];
                if (__el) {
                    let _c = source.filter(function (p) {
                        let p_date = new Date(p.Date);
                        let m_date = new Date(element.Date);
                        if (p_date - m_date == 0 && element.Resource_ID == p.Resource_ID && p.BzNbatch == 1) {
                            return p;
                        }
                    });
                    for (let index = 0; index < __el.Nbatch - _c.length; index++) {
                        addSpRows({
                            ParentID: element.ParentID,
                            Date: element.Date,
                            Resource_index: element.Resource_index,
                            Resource_ID: element.Resource_ID
                        }, theGrid.collectionView);
                    }
                }
            }
        }

    }
}

//自动排序，按设备大类的批数自动分摊
function AssessmentOfCapacity(source) {
    debugger;
    var WorkShopLine = getListWithMultParams("WorkShopLine", { Parent_ID: Isyc });
    temp = []; bc_temp = []; day_cout_ary = [];
    var month = new Date().getMonth() + 1;
    var day;
    var SchedulingLockDays = getTop().getConfigValue('SchedulingLockDays');
    if (IsInit) {
        day = new Date().getDate();
    } else {
        day = new Date().getDate() + SchedulingLockDays + 1;
    }

    var str = new Date().getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
    let myDate = JSON.stringify(str);
    var count = 0;
    let sb = {};

    foreach(source, function (item, i) {

        if (new Date(item.Date.format('yyyy-MM-dd')) >= new Date(str)) {

            if (!item) { return; }

            if (item.GcdType == -1) { return; }

            if (item.Number.length == 0) { return; }

            if (!IsInit) {
                if (!SchedulingLockDays) {
                    SchedulingLockDays = -1;
                }
                if (SchedulingLockDays > -1) {
                    let _d1 = new Date(addDate(new Date().format('yyyy-MM-dd'), parseInt(SchedulingLockDays)));
                    let _d2 = new Date(item.Date);
                    if (_d2 <= _d1) { return; }
                }
            }

            var res = nSelect(WorkShopLine, [[item.PlanNpkg, '>=', 'com_min'], [item.PlanNpkg, '<=', 'com_max']]);
            if (res) {
                if (sb[res.Code_ID] == null) {
                    sb[res.Code_ID] = 1;
                    myDate = JSON.stringify(str);
                }
                let fg = JSON.parse(myDate) + res.Code_ID;

                if (item.GcdType == 4 || item.GcdType == 5) {
                    if (temp[fg] == null) {
                        temp[fg] = item.Nbatch;
                    } else {
                        temp[fg] += item.Nbatch;
                    }
                } else {
                    if (item.Lock == 1) {
                        if (temp[fg] == null) {
                            temp[fg] = item.Nbatch;
                        } else {
                            temp[fg] += item.Nbatch;
                        }
                    }
                    if (temp[fg] == null) {
                        temp[fg] = item.Nbatch;
                        count++;
                        day_cout_ary[item.Resource_ID] = count;
                    }
                    if (temp[fg] >= res.Nbatch) {
                        if (item.GcdType != 4 && item.Lock == 0) {
                            //let n = SpRows(source, myDate, res.Code_ID);
                            item.Date = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                            item.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                            item.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                            item.Resource_ID = res.Code_ID;
                            item.index = i;
                            myDate = JSON.stringify(addDate(myDate, 1));
                            temp = [];
                        }
                        if (item.GcdType != 4 && item.Lock == 1) {
                            myDate = JSON.stringify(addDate(myDate, 1));
                            temp = [];
                        }
                    } else {
                        //let n = SpRows(source, myDate, res.Code_ID);
                        item.Date = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                        item.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                        item.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                        item.Resource_ID = res.Code_ID;
                        item.index = i;

                        if (item.GcdType != 4 || item.GcdType != 5) {
                            if (item.Lock == 0) {
                                temp[fg] += item.Nbatch;
                            }
                        }
                    }
                }
            } else {
                item.Resource_ID = 'Not';
            }
        }
    });
    return source;
}
//展开
let btnExpansion = Ext.create('Ext.Button', {
    tooltip: '展开',
    text: '展',
    glyph: 0xf103,
    handler: function () {
        theGrid.collapseGroupsToLevel(4);
    }
});
//收缩
let btnShrink = Ext.create('Ext.Button', {
    tooltip: '收缩',
    text: '收',
    glyph: 0xf102,
    handler: function () {
        theGrid.collapseGroupsToLevel(1);
    }
});
/***
 * 刷新工厂日历、班制、班次、全览表、车间档案
 * */
let RefreshData = function () {
    Wait.Start(null, "数据同步中.....");
    setTimeout(() => {
        sourceData();
        Wait.hide();
        Alert('提示：', '档案数据刷新完成');
    }, 1000);
}
/***
 * 导出Excel
 * 将当前界面的排产数据导出到Excel文件中
 * */
let ExportExcel = function () {
    Wait.Start(null, "正在执行操作，请稍候.....");
    setTimeout(() => {
        theGrid.collapseGroupsToLevel(3);
        theGrid.ExportExcel('工单粗排');
        theGrid.collapseGroupsToLevel(2);
        Wait.hide();
    }, 500);
}
/**
* 锁定工单
* 按产线、日期、班次进行批量锁定工单
**/
let LockTicket = function () {
    let source = theGrid.itemsSource.items;
    let resourceStore = Ext.create('Ext.data.Store', {
        fields: ['value', 'text'],
        data: []
    });
    let schedulingStore = Ext.create('Ext.data.Store', {
        fields: ['value', 'text'],
        data: []
    });
    let resourceCombox = Ext.create('Ext.form.ComboBox', {
        store: resourceStore,
        queryMode: 'local',
        displayField: 'text',
        valueField: 'value',
        editable: false
    });
    let dateField = {
        xtype: 'datefield',
        anchor: '100%',
        name: 'date',
        format: "Y/m/d",
        value: new Date()
    }
    let schedulingCombox = Ext.create('Ext.form.ComboBox', {
        store: schedulingStore,
        queryMode: 'local',
        displayField: 'text',
        editable: false,
        valueField: 'value'
    });
    let res_ary;
    res_ary = JsonArrayGroup(source);
    res_ary = theGrid.getColumn('Resource_ID').dataMap.collectionView.items;
    console.log(theGrid.getColumn('Resource_ID'));
    foreach(res_ary, function (item) {
        resourceStore.addSorted({
            value: item.id,
            text: item.name
        });
    });
    foreach(LocaltblItem, function (el) {
        schedulingStore.addSorted({
            value: el.FCode,
            text: el.FDescript
        });
    });
    let lockGrid = getTop().Ext.create('Ext.grid.Panel', {
        store: lockStore,
        region: 'south',
        frame: false,
        width: 900,
        height: '100%',
        viewConfig: {
            columnLines: true,
            stripeRows: true,
            enableTextSelection: true,
            animateShadow: true,
            forceFit: true
        },
        selModel: {
            mode: 'MULTI',
            checkboxSelect: true,
            injectCheckbox: 1,
            type: 'checkboxmodel'
        },
        plugins: {
            ptype: 'cellediting',
            clicksToEdit: 1
        },
        columns: [
            {
                header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true
            },
            {
                dataIndex: 'Resource_ID', header: '产线', width: 170, sortable: false, menuDisabled: true, editor: {
                    completeOnEnter: false, field: resourceCombox
                }, renderer: rendererCombobox(resourceCombox)
            },
            {
                dataIndex: 'Date', header: '日期', width: 120, sortable: false, menuDisabled: true,
                completeOnEnter: false, field: dateField, renderer: function (value) {
                    return value.format('yyyy/MM/dd');
                }
            },
            {
                dataIndex: 'Scheduling', header: '班次', hidden: true, width: 120, sortable: false, menuDisabled: true,
                completeOnEnter: false, field: schedulingCombox, renderer: function (value) {
                    let desc = LocaltblItem.filter(function (p) {
                        return p.FCode === value;
                    });
                    return desc.length == 0 ? '' : desc[0].FDescript;
                }
            }, {
                dataIndex: 'Lock', header: '锁定', width: 70, sortable: false, menuDisabled: true,
                completeOnEnter: false,
                field: Ext.create('Ext.form.ComboBox', {
                    store: Ext.create('Ext.data.Store', {
                        fields: ['value', 'text'],
                        data: [{ value: 1, text: '已锁' }, { value: 0, text: '未锁' }]
                    }),
                    queryMode: 'local',
                    displayField: 'text',
                    editable: false,
                    valueField: 'value',
                    value: 0
                }),
                renderer: function (value) {
                    return value == 1 ? '已锁' : '未锁';
                }
            }
        ],
        tbar: [
            {
                text: '新增',
                glyph: 0xf067,
                handler: function () {
                    lockStore.add({
                        Resource_ID: '',
                        Date: new Date(),
                        Scheduling: '',
                        Lock: 1,
                    });
                }
            },
            {
                text: '删除',
                glyph: 0xf2ed,
                handler: function () {
                    let rows = lockGrid.getSelection();
                    if (rows.length > 0) {
                        foreach(rows, function (rec) {
                            lockStore.remove(rec);
                        })
                    } else {
                        Alert('提示：', '请选择需要操作的数据');
                        return false;
                    }
                }
            }
        ]
    });
    var init_wind = Ext.create('Ext.window.Window', {
        title: '锁定工单',
        width: 600,
        height: '90%',
        modal: true,
        items: [lockGrid],
        fbar: [
            {
                type: 'button',
                text: '锁定',
                glyph: 0xf0c7,
                handler: function () {
                    let flg = LockGcd(source);
                    if (flg) {
                        Alert('提示：', '已完成！');
                        init_wind.close();
                    }
                }
            },
            {
                type: 'button',
                text: '取消',
                glyph: 0xf410,
                handler: function () {
                    init_wind.close();
                }
            }
        ]
    });
    init_wind.show();
}
/**
* 初始化数据
* 按工厂、产线、日期进行数据初始化
**/
let InitializationData = function () {
    var source = theGrid.itemsSource.sourceCollection;
    var view = theGrid.collectionView;
    var WorkShopLineMapData_Tmp = [];
    var YsCbox = new Ext.form.ComboBox({
        xtype: 'combobox',
        editable: false,
        fieldLabel: '岩彩/砂壁',
        store: new Ext.create('Ext.data.Store', {
            fields: ['value', 'text'],
            data: []
        }),
        displayField: 'text',
        valueField: 'value',
        queryMode: 'local',
        filterPickList: true,
        labelWidth: 50,
        listeners: {
            select: function (combo) {
                var val = combo.getValue();
                CxCbox.setValue(null);
                CxCbox.getStore().removeAll();
                CxCbox.resumeEvents();
                let shopline_ary = WorkShopLine.filter(function (p) {
                    if (p.Parent_ID == val) {
                        return p;
                    }
                });
                var cxCbox_data = [];
                WorkShopLineMapData_Tmp = [];
                foreach(shopline_ary, function (item) {
                    cxCbox_data.push({
                        value: item.Code_ID,
                        text: item.Description
                    });
                    WorkShopLineMapData_Tmp.push(item);
                });
                CxCbox.getStore().loadData(cxCbox_data);
                CxCbox.resumeEvents();
            }
        }
    });
    var CxCbox = new Ext.form.field.Tag({
        xtype: 'tagfield',
        fieldLabel: '产线',
        store: new Ext.create('Ext.data.Store', {
            fields: ['value', 'text'],
            data: []
        }),
        displayField: 'text',
        valueField: 'value',
        queryMode: 'local',
        filterPickList: true,
        labelWidth: 50
    });
    var init_wind = Ext.create('Ext.window.Window', {
        title: '初始化数据',
        width: 400,
        height: 300,
        modal: true,
        items: [
            {
                xtype: 'panel',
                layout: 'form',
                items: [
                    {
                        fieldLabel: '车间',
                        id: 'WIP_ID',
                        xtype: 'combobox',
                        editable: false,
                        queryMode: 'local',
                        valueField: 'value__',
                        displayField: 'TheNameValue',
                        store: getTop().newJsonStore({
                            fields: ['value__', 'TheNameValue'],
                            data: [
                                { "value__": "", "TheNameValue": "[无]" },
                                { "value__": "WIP_ID", "TheNameValue": "[浏览]" },
                            ]
                        }),
                        listeners: {
                            afterRender: function (combo) {
                                combo.setValue(combo.getStore().getAt(0).get("value__"));//同时下拉框会将与name为firstValue值对应的 text显示
                            },
                            select: function (combo) {
                                var c1 = combo.getValue();
                                var val;
                                var url = "/WorkShopLine?disble_operate_type=Add,Edit,Delete,Search&selectmode=true&ps=500&Type=1,2";
                                if (c1 == "WIP_ID") {
                                    combo.setValue(combo.getStore().getAt(0).get("value__"));
                                    getTop().openWindow("车间档案", url, 800, 600, function (v) {
                                        if (v != null && typeof (v) == "object") {
                                            if (v.length > 1) {
                                                if (v[0].success == 'true' || v[0].success == true) {
                                                    foreach(v, function (vitem) {
                                                        val = vitem.Code_ID;
                                                    });
                                                    var flg = 0;
                                                    for (var i = 0; i < combo.getStore().getCount(); i++) {
                                                        var recored = combo.getStore().getAt(i).get("value__");
                                                        if (recored == val) {
                                                            flg++;
                                                        }
                                                    }
                                                    if (flg == 0) {
                                                        combo.getStore().add({ value__: val, TheNameValue: val });
                                                    }
                                                    combo.setValue(val);
                                                    let shopline_ary = WorkShopLine.filter(function (p) {
                                                        if (p.Parent_ID == val) {
                                                            return p;
                                                        }
                                                    });
                                                    var cxCbox_data = [];
                                                    WorkShopLineMapData_Tmp = [];
                                                    foreach(shopline_ary, function (item) {
                                                        cxCbox_data.push({
                                                            value: item.Code_ID,
                                                            text: item.Description
                                                        });
                                                        WorkShopLineMapData_Tmp.push(item);
                                                    });
                                                    CxCbox.getStore().loadData(cxCbox_data);
                                                    CxCbox.resumeEvents();
                                                }
                                            }
                                        }
                                    }, "", null, null, isjsschema);
                                }
                                if (!c1) {
                                    CxCbox.getStore().removeAll();
                                    CxCbox.setValue(null);
                                    CxCbox.resumeEvents();
                                }
                            }
                        }
                    }, CxCbox,
                    {
                        fieldLabel: '排产天数',
                        id: 'pc_days',
                        name: 'pc_days',
                        value: 1,
                        xtype: 'numberfield',
                        AllowNegative: false,
                        minValue: 0,
                        maxValue: 100,
                        listeners: {
                            change: function (field, value) {
                                if (value == 0 || value < 0) {
                                    field.setValue(1);
                                }
                            }
                        }
                    }
                ]
            }
        ],
        fbar: [
            {
                type: 'button',
                text: '确定',
                handler: function () {
                    var pc_days = getTop().Ext.getCmp("pc_days").getRawValue();
                    let cxval_ary = CxCbox.getValue();
                    let cxtext_ary = CxCbox.getRawValue();
                    let cx_ary = [];
                    foreach(CxCbox.getValueRecords(),function (el) {
                        cx_ary.push({
                            value: el.get('value'),
                            text: el.get('text'),
                        });
                    })
                    if (cxtext_ary.length == 0) {
                        Alert('提示：', '请选择产线');
                        return false;
                    }
                    if (pc_days == 0 || pc_days < 0) {
                        Alert('提示：', '请填写正确的排产天数');
                        return false;
                    }
                    var WIP_ID = getTop().Ext.getCmp("WIP_ID").getRawValue();
                    Confirm('提示：', '确定初始化？', function () {
                        source.splice(0, source.length);
                        theGrid.collectionView.refresh();
                        debugger;
                        
                        foreach(cx_ary, function (item, j) {
                            var temp_date = new Date().format('yyyy/MM/dd');
                            getTop().ResourceIndex.push({
                                Resource_ID: item.value,
                                Index: j
                            });
                            let wk_arry = WorkShopLine.filter(function (p) {
                                if (p.Code_ID == item.value) { return p; }
                            });
                            let __el = wk_arry[0];
                            for (var i = 0; i < pc_days; i++) {
                                var newItem = new Object();//view.addNew();
                                newItem.ParentID = WIP_ID;
                                newItem.GcdType = -1;
                                newItem.IsBz = 1;
                                newItem.BzNbatch = 1;
                                newItem.Date = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                newItem.Resource_index = j;
                                newItem.Resource_ID = item.value;
                                newItem.Resource = item.text;
                                newItem.Number = '';
                                newItem.Inventory_ID = '';
                                newItem.Description = '';
                                newItem.BatchNO = '';
                                newItem.PlanQty = 0;
                                newItem.Nbatch = 1;
                                newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                newItem.PlanDate = 0;
                                newItem.MfgCatID = '';
                                newItem.SandTypeId = '';
                                newItem.SaOrderKey = 0;
                                newItem.FStatus = '';
                                newItem.Lock = 0;
                                newItem.Capacity = 0;
                                newItem.OnePlanMAX = '';
                                newItem.StdInventory_ID = '';
                                newItem.PlanDateEnd = '';
                                newItem.Matching = '';
                                newItem.Style = '';
                                newItem.Capacity = 0;
                                newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                FlexGridInsert(newItem);
                                temp_date = addDate(temp_date, 1);
                            }

                        });
                        var WorkShopLineMapData = new Array();
                        foreach(WorkShopLineMapData_Tmp, function (it) {
                            WorkShopLineMapData.push(it);
                        })
                        theGrid.RefreshColumnDataMap(WorkShopLineMapData);
                        init_wind.close();
                        theGrid.collectionView.refresh();
                        theGrid.collapseGroupsToLevel(3);
                        IsInit = false;
                    }, function () { }, null);
                }
            },
            {
                type: 'button',
                text: '取消',
                handler: function () {
                    init_wind.close();
                }
            }
        ]
    });
    init_wind.show();
}
/**
 * 删除
 * 将选择的行记录数据从当前排产界面中移除
 * */
let wijmoDelete = function () {
    var cv = theGrid.itemsSource;
    if (cv.currentItem) {
        Confirm('提示：', '确定删除？', function () {
            cv.remove(cv.currentItem);
            cv.refresh();
        }, null, null);
    } else {
        Alert('提示：', '请选择操作项！');
        return false;
    }
}
//虚拟工单
let VirtualTicketRead = function () {
    let source = theGrid.itemsSource.sourceCollection;
    let gd_arry = [];

    foreach(source, function (item, i) {
        if (item.GcdType == 4) {
            gd_arry.push(item.Number.match(/(\S*)-/)[1]);
        }
    });
    function wnd(list) {
        foreach(list, function (el) {
            var work = WorkShopLine.filter(function (p) {
                if (p.Code_ID == el.Factory) {
                    return p;
                }
            });
            var line = WorkShopLine.filter(function (p) {
                if (p.Code_ID == el.ProductionLine) {
                    return p;
                }
            });
            var ResCategory = WorkShopLine.filter(function (p) {
                if (p.Code_ID == el.ResCategory) {
                    return p;
                }
            });
            el.Factory_name = work.length == 0 ? "" : work[0].Description;
            el.ProductionLine_name = line.length == 0 ? "" : line[0].Description;
            el.ResCategory_name = ResCategory.length == 0 ? "" : ResCategory[0].Description;
        });
        var store = Ext.create('Ext.data.Store', {
            fields: ['EvidenceNumber', 'Factory', 'Factory_name', 'ResCategory', 'ResCategory_name', 'ProductionLine', 'ProductionLine_name', 'BeginDate', 'EndDate', 'Maker', 'SumWrkHour', 'SumCapacity', 'Reason', 'Summary'],
            data: list
        });
        var grid = getTop().Ext.create('Ext.grid.Panel', {
            store: store,
            region: 'south',
            frame: false,
            width: 900,
            height: '100%',
            viewConfig: {
                columnLines: true,
                stripeRows: true,
                enableTextSelection: true,
                animateShadow: true,
                forceFit: true
            },
            selModel: {
                mode: 'Single',
                checkboxSelect: true,
                injectCheckbox: 1,
                type: 'checkboxmodel'
            },
            columns: [
                { header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
                { dataIndex: 'EvidenceNumber', header: '工单号', width: 120, sortable: false, menuDisabled: true },
                { dataIndex: 'Factory', header: '工厂', hidden: true, width: 109, sortable: false, menuDisabled: true },
                { dataIndex: 'Factory_name', header: '工厂', width: 109, sortable: false, menuDisabled: true },
                { dataIndex: 'ProductionLine', header: '产线', hidden: true, width: 87, sortable: false, menuDisabled: true },
                { dataIndex: 'ProductionLine_name', header: '产线', width: 109, sortable: false, menuDisabled: true },
                { dataIndex: 'ResCategory', header: '设备大类', width: 109, sortable: false, menuDisabled: true },
                { dataIndex: 'ResCategory_name', header: '设备大类', width: 109, sortable: false, menuDisabled: true },
                { dataIndex: 'BeginDate', header: '开始日期', width: 112, sortable: false, menuDisabled: true },
                { dataIndex: 'EndDate', header: '截止日期', width: 112, sortable: false, menuDisabled: true },
                { dataIndex: 'SumWrkHour', header: '总虚拟工时', width: 74, sortable: false, menuDisabled: true },
                { dataIndex: 'SumCapacity', header: '总虚拟产能', width: 61, sortable: false, menuDisabled: true },
                { dataIndex: 'Reason', header: '原因', width: 100, sortable: false, menuDisabled: true },
                { dataIndex: 'Summary', header: '备注', width: 74, sortable: false, menuDisabled: true },
                { dataIndex: 'Maker', header: '制单人', width: 200, sortable: false, menuDisabled: true },
            ]
        });
        var init_wind = getTop().Ext.create('Ext.window.Window', {
            title: '虚拟工程单',
            width: 830,
            height: 480,
            modal: true,
            maximizable: true,
            items: [grid],
            listeners: {
                resize: function (wn, width, height, eOpts) {
                    let grid = wn.items.items[0];
                    grid.setHeight(height - 80);
                    grid.setWidth(width - 15);
                }
            },
            fbar: [
                {
                    type: 'button',
                    text: '选择',
                    handler: function () {
                        let selectrows = grid.getSelectionModel().getSelection();
                        if (selectrows.length > 0) {
                            let selectrow = selectrows[0].data;
                            let child_list = getListWithMultParams("TblVirtualTicketDetails", { EvidenceNumber: selectrow.EvidenceNumber });
                            foreach(child_list, function (item, i) {
                                i = i + 1;
                                let view = theGrid.collectionView;
                                if (item.Nbatch && item.Nbatch > 0) {
                                    for (let index = 0; index < item.Nbatch; index++) {
                                        let newItem = view.addNew();
                                        newItem.Resource_ID = item.ResCategory;
                                        newItem.index = 0;
                                        newItem.Resource_index = 1;
                                        newItem.ParentID = selectrow.Factory;
                                        newItem.Date = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
                                        newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
                                        newItem.Inventory_ID = '虚拟工单';
                                        newItem.Lock = 1;
                                        newItem.Number = `${item.EvidenceNumber}-${item.NOID}-${index + 1}`;
                                        newItem.PlanQty = item.VirtualCapacity;
                                        newItem.Nbatch = 1;
                                        newItem.PlanDate = item.VirtualWork;
                                        newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
                                        newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
                                        newItem.GcdType = 4;
                                        newItem.Summary = item.Reason != null && item.Reason != "" ? item.Reason + ':' + selectrow.Summary : selectrow.Summary;
                                        view.commitNew();
                                    }
                                }
                            });
                            theGrid.collectionView.refresh();
                            init_wind.close();
                            return true;
                        } else {
                            Alert('提示：', '请选择数据！');
                            return false;
                        }
                    }
                }, {
                    type: 'button',
                    text: '取消',
                    handler: function () {
                        init_wind.close();
                    }
                }
            ]
        });
        init_wind.show();
    }
    gd_arry = gd_arry.distinct();
    var cond = {
        t: "and", child: [
            { c: "EvidenceNumber", cp: 'notin', v: gd_arry.join(';') },
            { c: "Verify", cp: '=', v: 1 }
        ]
    }
    Wait.Start(null, "正在执行操作，请稍候.....");
    list = getListWithMultParams("TblVirtualTicket", { _cdt: jsonEncode(cond) }, null, {
        callback: function (vitems) {
            Wait.hide();
            wnd(vitems);
        },
        async: function () { }
    });
}

let VirtualTicketEdit = function () {
    let cv = theGrid.itemsSource;
    let row = cv.currentItem;
    if (row.GcdType == 4) {
        let Gcd_No = row.Number.match(/(\S*)-/)[1];
        let source = theGrid.itemsSource.items;
        let gd_status = getListWithMultParams("TblVirtualTicket", { EvidenceNumber: '=' + Gcd_No });
        if (Gcd_No == null || Gcd_No == "" || Gcd_No == undefined) {
            Alert('提示：', '请选择需要修改的虚拟工单！');
            return false;
        } else if (gd_status[0].Verify == 1) {
            Alert('提示：', '该工单已审核，无法编辑！');
            return false;
        } else {
            getTopWindow().openWindow("虚拟工单", "/TblVirtualTicket/edit?editmode=true&EvidenceNumber=" + Gcd_No, 900, 600, function (v) {
                if (v != null && v[0].success == true) {
                    let child_list = getListWithMultParams("TblVirtualTicketDetails", { EvidenceNumber: v[1].EvidenceNumber });
                    foreach(child_list, function (el, i) {
                        i = i + 1;
                        for (let i = 0; i < source.length; i++) {
                            let p = source[i];
                            if (p.Number === el.EvidenceNumber + '-' + el.NOID) {
                                p.Resource_ID = el.ResCategory;
                                p.Resource_index = 1;
                                p.index = 0;
                                p.ParentID = v[1].Factory;
                                p.Date = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
                                p.PlanDateStart = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
                                p.Inventory_ID = '虚拟工单';
                                p.Number = el.EvidenceNumber + '-' + el.NOID;
                                p.PlanQty = el.VirtualCapacity;
                                p.PlanDate = el.VirtualWork;
                                p.Nbatch = el.Nbatch;
                                p.Lock = 1;
                                p.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
                                p.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
                                p.Summary != null && el.Reason != "" ? el.Reason + ':' + v[1].Summary : v[1].Summary;
                                p.GcdType = 4;
                            }
                        }
                    });
                    theGrid.collectionView.refresh();
                }
            });
        }
    } else {
        Alert('提示：', '请选择虚拟工单！');
        return false;
    }
}

//结果保存
let wijmoSave = function () {
    var source = theGrid.itemsSource.items;
    //计划主表：ProductionPlanGcd
    // 设置要打开窗口的地址，打开的表用编码表示，此处打开订单表（以创建模式打开）
    var url = "/ProductionPlanGcd/edit?createmode=true";

    // 将查询字符串固定的参数添加到url中，每次打开的窗口都有一些固定的参数存在，如制定数据库编号
    var urlarg = new Array();

    foreach(__fq, function (v, i, leave, name) { urlarg.push(name + "=" + encodeURIComponent(v)); });

    url += "&" + urlarg.join("&");
    var updatelist = new Array();
    // 打开编辑对话框，函数定义见main.js
    parent.openWindow("工单粗排计划", url, 900, 600,
        function () {
            Batch.updateDatabase(updatelist, false, function (vback) {
                var vitem = vback[0];
                debugger
                if (vitem.success === false) {
                    Alert("", vitem.message);
                }
                else {
                    ShowToast("操作成功！");
                }
            });
        }, 0xf067,
        // openWindow 的参数initwnd，当窗口打开后执行，设置窗口界面加载完成所执行的函数
        function (newwnd) {
            var childFrame = newwnd.getChildFrame('ProductionPlanGcdDetail');

            var table = "TblVirtualTicket";
            var childtable = "TblVirtualTicketDetails";
            Wait.Start(null, "正在执行操作，请稍候.....");
            setTimeout(() => {
                let evi = newwnd.getValue(null, 'ProductionNo');
                evi = evi.replace(evi[0], 'T');
                source.sort(function (a, b) { a.index - b.index });
                foreach(source, function (v, i) {
                    if (v.GcdType >= 0) {
                        var def = Math.round((new Date(v.PlanDateEnd) - new Date(v.ScheduleEndDate)) / 1000 / 60 / 60 / 24);
                        var obj = new Object();
                        obj.WIP_ID = v.ParentID;
                        obj.Noid = i;
                        obj.CreateDate = v.Date;
                        obj.Resource_index = v.Resource_index;
                        obj.Scheduling = v.Scheduling;
                        obj.IssuleNo = v.Number;
                        obj.ScheduleStartDate = v.ScheduleEndDate;        //lab31-211007   SaOrderKey
                        obj.ScheduleEndDate = v.ScheduleEndDate;
                        obj.ScheduleDateDifference = def;
                        obj.CustomerKey = v.CustomerKey; //.substring(s.lastIndexOf("/") + 1);  //lab31-211007
                        obj.BatchNO = v.BatchNO;
                        obj.SaOrderKey = v.SaOrderKey;
                        obj.BzNbatch = v.BzNbatch;
                        obj.Nbatch = v.Nbatch;
                        obj.PlanNpkg = v.PlanNpkg;
                        obj.StdInventory_ID = v.StdInventory_ID;
                        obj.MfgCatID = v.MfgCatID;
                        obj.Unit_Weight = v.Unit_Weight;
                        obj.HCapacity = v.HCapacity;
                        obj.Summary = v.Summary;
                        obj.Matching = v.Matching;
                        obj.MatchingTime = v.MatchingDate;
                        obj.Resource_ID = v.Resource_ID;
                        obj.Inventory_id = v.Inventory_ID;
                        obj.PbeginDate = v.PlanDateStart;
                        obj.PEndDate = v.PlanDateEnd;
                        obj.MfgPlanTime = v.PlanDate;
                        obj.IssueQty = v.PlanQty;
                        obj.ProQty = v.PlanQty;
                        obj.Lock = v.Lock;
                        obj.KDAUF = v.KDAUF;
                        obj.KDPOS = v.KDPOS;

                        if (v.GcdType == 5) {
                            updatelist.push(new UpdateItemObject(table, {
                                Type: 1,
                                EvidenceNumber: evi + 1,
                                Factory: v.ParentID,
                                ProductionLine: v.Isyc,
                                BeginDate: v.Date,
                                EndDate: v.Date,
                                Maker: getTop().username,
                                SumWrkHour: 0,
                                SumCapacity: 0,
                                Reason: v.Number + '拖单',
                                Summary: v.Number + '拖单',
                                Status: 0
                            }, Action.Add));
                            updatelist.push(new UpdateItemObject(childtable, {
                                NOID: 1,
                                EvidenceNumber: evi + 1,
                                Factory: v.ParentID,
                                Shift: '001',
                                ResCategory: v.Resource_ID,
                                Date: v.Date,
                                StandardHours: 0,
                                TimeWorked: 0,
                                AvailableWork: 0,
                                StandardCapacity: 0,
                                OpenCapacity: 0,
                                AvailableCapacity: 0,
                                VirtualWork: 0,
                                VirtualCapacity: 0,
                                Nbatch: v.Nbatch,
                                Reason: v.Number + '拖单'
                            }, Action.Add));
                        }
                        childFrame.addChildRow(obj);
                    }
                });
                newwnd.setPropertyValue(null, 'Type', 2);
                newwnd.setPropertyValue(null, 'WIP_ID', source[0].ParentID);

                Wait.hide();
            }, 1000);
        }, null, isjsschema);
}

//自动排序
let AutomaticSorting = function () {
    debugger;
    var source = theGrid.itemsSource.items;
    AssessmentOfCapacity(source.sort(function (a, b) { return a.index - b.index }));
    let cv = theGrid.itemsSource;
    for (let index = 0; index < source.length; index++) {
        const element = source[index];
        if (element.Number.length == 0) {
            cv.remove(element);
            cv.refresh();
        }
    }
    theGrid.refresh();
    theGrid.collectionView.refresh();
    AssessAddSpRows(theGrid.itemsSource.items);
    theGrid.collectionView.refresh();
}

/**
 * 配置总览
 */
let OptimizedConfiguration = function () {
    let row = theGrid.getSelectItem();
    if(!row){
        Alert('提示：',"请选择需要查看工单")
        return false;
    }
    if(!row.Inventory_ID){
        Alert('提示：',"")
        return false;
    }
    getTopWindow().openWindow("配置总览", "/Inventory/Edit?viewmode=true&Inventory_ID="+row.Inventory_ID, 1000, 500, function () { }, "", "", null, isjsschema);
}

/**
 * 数组查询按条件默认返回第一行记录
 **/
Array.prototype.filterItem = function (param) {
    var arr = this, pms = '';
    if (param) {
        for (var j = 0; j < param.length; j++) {
            let el = param[j];
            if (j == param.length - 1) {
                pms += `'${el.v}'${el.c}el['${el.f}']`
                break;
            }
            pms += `'${el.v}'${el.c}el['${el.f}'] && `;
        }
    }
    for (let i = 0; i < arr.length; i++) {
        let el = arr[i];
        if (eval(pms)) {
            return el;
        }
    }
}

//读取未完工单
let NotFinishProductionOrder = function () {
    var rows = theGrid.getSelectItem();
    var source = theGrid.itemsSource.items;
    var gd_arry = [];
    var cond = {
        t: "and", child: []
    }
    foreach(source, function (item) {
        if (item.Number) {
            gd_arry.push(item.Number);
        }
    });
    function wnd(list, rows) {
        var WorkShopLine = getListWithMultParams("WorkShopLine", { Parent_ID: rows.ParentID });
        var store = Ext.create('Ext.data.Store', {
            fields: ['Des_StockID', 'NO', 'BatchNO', 'JiHao', 'JiHaoName', 'Inventory_ID', 'Description', 'STYLE', 'CQty', 'PlanNpkg', 'Unit', 'WrkHrs', 'KDAUF', 'KDPOS', 'ReqDate', 'DuDate', 'CUST', 'Project', 'VIP', 'SelfMfg_OrdersPO', 'Date', 'IsProduceResIssuePlan', 'Summary', 'Type'],
            sortable: true,
            sorters: [{ property: "ReqDate", direction: "ASC" }], //给定一个默认的排序方式      
            data: list
        });
        foreach(gd_arry, function (c) {
            let record = store.findExact('NO', c);
            if (record > -1) {
                store.removeAt(record);
            }
        });
        store.each(function (record) {
            //按照物料号+是否岩彩砂壁+工厂    查询成品分类编码数据
            let invList = AllSettings.find(x => x.Inventory_ID === record.get('Inventory_ID'));
            if (record.get('Type') == 2) {
                invList = AllSettings.find(x => x.Inventory_ID === record.get('Inventory_ID'));
            }
            if (!invList) {
                store.remove(record);
            } else {
                let el = record.getData();
                // var inv = AllSettings.filter(function (p) {
                //     if (p.Inventory_ID == el.Inventory_ID) {
                //         return p;
                //     }
                // });
                var PlanNpkg = el.CQty;
                if (el.Unit == 'KG') {
                    if (invList) {
                        PlanNpkg = parseInt(el.CQty / invList.STYLE);
                        record.set('STYLE', invList.STYLE);
                    }
                    record.set('PlanNpkg', PlanNpkg);
                }
                if (el.Unit == 'DR') {
                    let CQty = 0;
                    if (invList) {
                        CQty = parseInt(el.CQty * invList.STYLE);
                        record.set('STYLE', invList.STYLE);
                    } else {
                        let tp = AllSettings.find(x => x.Inventory_ID === el.Inventory_ID);
                        if (tp.length > 0) {
                            CQty = parseInt(el.CQty * tp.STYLE);
                            record.set('STYLE', tp.STYLE);
                        }
                    }
                    record.set('PlanNpkg', el.CQty);
                    record.set('CQty', CQty);
                }
                var res = nSelect(WorkShopLine, [[PlanNpkg, '>=', 'com_min'], [PlanNpkg, '<=', 'com_max']]);
                if (res) {
                    record.set('JiHao', res.Code_ID);
                    record.set('JiHaoName', res.Description);
                }
                record.set('Description', invList.Description);
            }
        });
        store.filterBy(function (item) {
            return item.data.JiHao == rows.Resource_ID || item.data.JiHao == '';
        });
        var grid = getTop().Ext.create('Ext.grid.Panel', {
            store: store,
            region: 'south',
            frame: false,
            width: 900,
            height: '100%',
            viewConfig: {
                columnLines: true,
                stripeRows: true,
                enableTextSelection: true,
                animateShadow: true,
                forceFit: true,
                getRowClass: function (record) {
                    let nowDate = new Date().format('yyyy/MM/dd');
                    let tmdate = new Date(record.data.DuDate).format('yyyy/MM/dd');;
                    if (tmdate < nowDate) {
                        return "bglightred";
                    }
                }
            },
            selModel: {
                mode: 'MULTI',
                checkboxSelect: true,
                injectCheckbox: 1,
                type: 'checkboxmodel'
            },
            plugins: {
                gridfilters: true
            },
            columns: [
                { header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
                {
                    dataIndex: 'Des_StockID', header: '车间', width: 51, sortable: false, menuDisabled: false,
                    filter: {
                        type: 'string', itemDefaults: { emptyText: '查询...' }
                    }
                },
                { dataIndex: 'NO', header: '工程单号', width: 109, sortable: false, menuDisabled: true },
                {
                    dataIndex: 'JiHao', header: '设备大类', hidden: true, width: 87, sortable: false, menuDisabled: false

                },
                { dataIndex: 'JiHaoName', header: '设备大类', width: 87, sortable: false, menuDisabled: true },
                { dataIndex: 'VIP', header: 'VIP', width: 112, sortable: false, menuDisabled: true },
                { dataIndex: 'BatchNO', header: '批次号', width: 112, sortable: false, menuDisabled: true },
                { dataIndex: 'KDAUF', header: '销售订单', width: 112, sortable: false, menuDisabled: true },
                { dataIndex: 'KDPOS', header: '销售订单行项目', width: 112, sortable: false, menuDisabled: true },
                { dataIndex: 'LvWanAct', header: '半成品工单号', width: 112, sortable: false, menuDisabled: true },
                { dataIndex: 'Inventory_ID', header: '成品', width: 112, sortable: false, menuDisabled: true },
                { dataIndex: 'Description', header: '成品名称', width: 200, sortable: false, menuDisabled: true },
                { dataIndex: 'STYLE', header: '规格', width: 74, sortable: false, menuDisabled: true },
                { dataIndex: 'CQty', header: '生产总量', width: 74, sortable: false, menuDisabled: true },
                { dataIndex: 'PlanNpkg', header: '目标数量', width: 74, sortable: false, menuDisabled: true },
                { dataIndex: 'Unit', header: '单位', width: 74, sortable: false, menuDisabled: true },
                { dataIndex: 'WrkHrs', header: '总工时', width: 61, sortable: false, menuDisabled: true },
                { dataIndex: 'ReqDate', header: '计划工开时间', width: 140, sortable: false, menuDisabled: true },
                { dataIndex: 'DuDate', header: '要求完成时间', width: 140, sortable: false, menuDisabled: true },
                { dataIndex: 'CUST', header: '客户编码', width: 74, sortable: false, menuDisabled: true },
                { dataIndex: 'Project', header: '计划单号', width: 74, sortable: false, menuDisabled: true },
                { dataIndex: 'SelfMfg_OrdersPO', header: '车间加工计划号', width: 100, sortable: false, menuDisabled: true },
                { dataIndex: 'Date', header: '开单日期', width: 140, sortable: false, menuDisabled: true },
                { dataIndex: 'IsProduceResIssuePlan', header: '排程状态', width: 100, sortable: false, menuDisabled: true },
                { dataIndex: 'Summary', header: '备注', width: 100, sortable: false, menuDisabled: true },
                { dataIndex: 'Type', header: '工单类型', width: 100, sortable: false, hidden: true, menuDisabled: true }
            ]
        });
        var init_wind = getTop().Ext.create('Ext.window.Window', {
            title: '未清生产工单',
            width: 830,
            height: 480,
            modal: true,
            maximizable: true,
            items: [grid],
            listeners: {
                resize: function (wn, width, height, eOpts) {
                    let grid = wn.items.items[0];
                    grid.setHeight(height - 80);
                    grid.setWidth(width - 15);
                }
            },
            fbar: [
                {
                    type: 'button',
                    text: '选择',
                    handler: function () {
                        let selectrows = grid.getSelectionModel().getSelection();
                        let xntd = [];
                        let view = theGrid.collectionView;
                        if (selectrows.length > 0) {
                            for (var i = 0; i < selectrows.length; i++) {
                                let item = selectrows[i].data;
                                let nowDate = new Date().format('yyyy/MM/dd');
                                let end_date, start_date;
                                if (new Date(item.DuDate) < new Date(nowDate)) {
                                    end_date = nowDate;
                                    start_date = nowDate
                                } else {
                                    if (IsInit) {
                                        end_date = item.DuDate;
                                        start_date = item.ReqDate;
                                    } else {
                                        end_date = addDate(item.ReqDate, 3);
                                        start_date = addDate(item.DuDate, 3);
                                    }
                                }
                                let __n = SpRows(theGrid.itemsSource.items, end_date, item.JiHao);
                                if (IsNumber(__n)) {
                                    const element = theGrid.itemsSource.items[__n];
                                    theGrid.beginUpdate();
                                    element.KDAUF = item.KDAUF;       //新增加   lab31-211007
                                    element.KDPOS = item.KDPOS;       //element.KDPOS = rows.KDPOS;  lab31-211007
                                    element.LvWanAct = item.LvWanAct;  //element.LvWanAct = item.LvWanAct;   lab31-211007
                                    element.ParentID = rows.ParentID;
                                    element.CustomerKey = item.VIP;       //lab31-211007
                                    element.FStatus = item.FStatus;
                                    element.Capacity = item.Capacity;
                                    element.Resource_ID = item.JiHao;
                                    element.Resource_index = rows.Resource_index;
                                    element.Number = item.NO;
                                    element.Inventory_ID = item.Inventory_ID;
                                    element.Description = item.Description;
                                    element.BatchNO = item.BatchNO;
                                    element.PlanQty = item.CQty;
                                    element.Nbatch = 1;
                                    element.Unit = item.Unit;
                                    element.Lock = 0;
                                    element.PlanNpkg = item.PlanNpkg;
                                    element.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.ReqDate, 'yyyy/MM/dd');
                                    element.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.DuDate, 'yyyy/MM/dd');
                                    element.Matching = item.Matching;
                                    element.Unit_Weight = item.STYLE;
                                    element.GcdType = 0;
                                    element.SaOrderKey = 0;
                                    element.Summary = item.Summary;
                                    element.Date = getTop().wijmo.Globalize.parseDate(end_date, 'yyyy/MM/dd');
                                    element.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(end_date, 'yyyy/MM/dd');
                                    element.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(start_date, 'yyyy/MM/dd');
                                    view.refresh();
                                    theGrid.endUpdate();
                                    if (new Date(item.DuDate) < new Date(nowDate)) {
                                        xntd.push(element);
                                    }
                                } else {
                                    var newItem = new Object();
                                    newItem.KDAUF = item.KDAUF;    //新增加   lab31-211007
                                    newItem.KDPOS = item.KDPOS;     //newItem.KDPOS = rows.KDPOS;  lab31-211007
                                    newItem.LvWanAct = item.LvWanAct;    //newItem.LvWanAct = rows.LvWanAct;  lab31-211007
                                    newItem.ParentID = rows.ParentID;
                                    newItem.CustomerKey = item.VIP;     //newItem.VIP = rows.VIP;    //lab31-211007
                                    newItem.BzNbatch = 0;
                                    newItem.FStatus = item.FStatus;
                                    newItem.Capacity = item.Capacity;
                                    newItem.Resource_ID = item.JiHao;
                                    newItem.Resource_index = rows.Resource_index;
                                    newItem.Number = item.NO;
                                    newItem.Inventory_ID = item.Inventory_ID;
                                    newItem.Description = item.Description;
                                    newItem.BatchNO = item.BatchNO;
                                    newItem.PlanQty = item.CQty;
                                    newItem.Nbatch = 1;
                                    newItem.Unit = item.Unit;
                                    newItem.Lock = 0;
                                    newItem.PlanNpkg = item.PlanNpkg;
                                    newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.ReqDate, 'yyyy/MM/dd');
                                    newItem.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.DuDate, 'yyyy/MM/dd');
                                    newItem.Matching = item.Matching;
                                    newItem.Unit_Weight = item.STYLE;
                                    newItem.GcdType = 0;
                                    newItem.SaOrderKey = 0;
                                    newItem.Summary = item.Summary;
                                    newItem.Date = getTop().wijmo.Globalize.parseDate(end_date, 'yyyy/MM/dd');
                                    newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(end_date, 'yyyy/MM/dd');
                                    newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(start_date, 'yyyy/MM/dd');
                                    FlexGridInsert(newItem);
                                    if (new Date(item.DuDate) < new Date(nowDate)) {
                                        xntd.push(newItem);
                                    }
                                }
                            }
                            theGrid.collectionView.refresh();
                            AssessAddSpRows(theGrid.itemsSource.items);

                            init_wind.close();
                            return true;
                        } else {
                            Alert('提示：', '请选择数据！');
                            return false;
                        }
                    }
                }, {
                    type: 'button',
                    text: '取消',
                    handler: function () {
                        init_wind.close();
                    }
                }
            ]
        });
        init_wind.show();
    }

    let con_ary = [
        { c: "Closed", cp: '=', v: 0 },
        { c: "Des_StockID", cp: '=', v: rows.ParentID }
    ];
    if (gd_arry.length > 0) {
        con_ary.push({ c: "NO", cp: 'notin', v: gd_arry.join(";") })
    }
    cond.child = con_ary;
    Wait.Start(null, "正在执行操作，请稍候.....");
    list = getListWithMultParams("Material_Issue_Plan", { _cdt: jsonEncode(cond) }, null, {
        callback: function (vitems) {
            Wait.hide();
            wnd(vitems, rows == undefined ? '' : rows);
        },
        async: function () {

        }
    });
}
/***
 * 齐套分析
 * 排产界面中的工单与sap给的数据做对比，齐套标记绿色，不齐套标记红色
*/
let BundleAnalysis = function () {
    let cv = theGrid.itemsSource;
    var source = theGrid.itemsSource.items;
    let Des_StockID = cv.currentItem.ParentID
    var gd_arry = [];

    Wait.Start(null, "正在执行操作，请稍候.....");
    foreach(source, function (item, i) {
        //if (cv.currentItem.Resource_ID == item.Resource_ID) {
        if (item.Number != null && item.Number != undefined && item.Number != "") {
            gd_arry.push(item.Number);
        }
        //}
    });
    let _cond = {
        t: "and", child: [
            { c: "NO", cp: 'in', v: gd_arry.join(";") },
            { c: "Des_StockID", cp: '=', v: Des_StockID }
        ]
    }
    let bcplist = getListWithMultParams("Material_Issue_Plan", { _cdt: jsonEncode(_cond) });
    foreach(source, function (item) {
        //if (cv.currentItem.Resource_ID == item.Resource_ID) {
        var temp = bcplist.find(x => x.NO == item.Number);
        if (temp) {
            if (temp.Closed == 1) {
                item.Matching = 3;
            } else {
                item.Matching = temp.Matching == null ? 0 : temp.Matching;
                item.MatchingDate = temp.MatchingDate;
            }
        }
        //}
    });
    theGrid.collectionView.refresh();
    Alert('提示：', '齐套分析完成');
}
/**
* 读当天计划
* 读取当前的排产计划到当前的排产界面
**/
let ReadNowPlan = function () {
    var source = theGrid.itemsSource.sourceCollection;
    var WorkShopLineMapData_Tmp = [];
    getTopWindow().openWindow("当天排产计划", "/ProductionPlanGcd?disble_operate_type=Add,Edit,Delete,Print,Record,BackRecord,Verify,Search&selectmode=true&Maker=" + getTopWindow().username + "&MakeDate=" + Common.formatDate(now, 'yyyy/MM/dd'), 900, 600, function (v) {
        if (v != null && typeof (v) == "object") {
            if (v.length == 2) {
                source.splice(0, source.length);
                var child_list = getListWithMultParams("ProductionPlanGcdDetail", { ProductionNo: v[1].ProductionNo });
                child_list.sort(function (a, b) { return a.Noid - b.Noid });
                theGrid.collectionView.refresh();
                let ccArry = {};
                var view = theGrid.collectionView;
                if (child_list.length == 0) {
                    return;
                }
                var WorkShopLineMapData = new Array();
                foreach(WorkShopLineMapData_Tmp, function (it) {
                    WorkShopLineMapData.push(it);
                })
                theGrid.RefreshColumnDataMap(WorkShopLineMapData);
                foreach(child_list, function (item) {
                    var GdItem = getItem('Material_Issue_Plan', 'NO', item.IssuleNo);
                    if (item.IssuleNo || item.IssuleNo.indexOf("XGCD") == 0 || item.IssuleNo.indexOf("T") == 0) {
                        let ScheduleEndDate = new Date(item.ScheduleEndDate).format('yyyy/MM/dd');
                        let temp_allsetting = AllSettings.find(x => x.Inventory_ID == item.Inventory_id);
                        if (ccArry[item.Resource_ID + ScheduleEndDate] == null) {
                            ccArry[item.Resource_ID + ScheduleEndDate] = 1;
                            let temp = WorkShopLine.filter(function (p) {
                                if (item.Resource_ID == p.Code_ID) {
                                    return p;
                                }
                            });
                            let __el = temp[0];
                            if (__el) {
                                for (let index = 0; index < __el.Nbatch; index++) {
                                    addSpRows({
                                        ParentID: item.WIP_ID,
                                        Date: ScheduleEndDate,
                                        Resource_index: item.Resource_index,
                                        Resource_ID: item.Resource_ID
                                    }, view);
                                }
                            }
                        }
                        let __n = SpRows(source, ScheduleEndDate, item.Resource_ID);
                        if (IsNumber(__n)) {
                            let _elment = source[__n];
                            theGrid.beginUpdate();
                            _elment.Resource_ID = item.Resource_ID;
                            _elment.Resource_index = item.Resource_index;
                            _elment.ParentID = item.WIP_ID;
                            _elment.Date = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                            _elment.Inventory_ID = item.Inventory_id;
                            _elment.Description = GdItem.Summary1;//temp_allsetting.length > 0 ? temp_allsetting[0].Description : '';
                            _elment.Number = item.IssuleNo;
                            _elment.BatchNO = item.BatchNO;
                            _elment.PlanQty = item.IssueQty;
                            _elment.Nbatch = item.Nbatch;
                            _elment.BzNbatch = item.BzNbatch;
                            _elment.IsBz = item.BzNbatch;
                            _elment.Lock = 0;
                            _elment.SaOrderKey = item.SaOrderKey;
                            _elment.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.PbeginDate, 'yyyy/MM/dd');
                            _elment.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.PEndDate, 'yyyy/MM/dd');
                            _elment.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.ScheduleStartDate, 'yyyy/MM/dd');
                            _elment.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                            _elment.PlanDate = item.MfgPlanTime;
                            _elment.PlanNpkg = item.PlanNpkg;
                            _elment.StdInventory_ID = item.StdInventory_ID;
                            _elment.MfgCatID = item.MfgCatID;
                            _elment.HCapacity = item.HCapacity;
                            _elment.Summary = item.Summary;
                            _elment.Matching = item.Matching;
                            _elment.SaOrderKey = item.SaOrderKey ? item.SaOrderKey : 0;
                            _elment.ScheduleDateDifference = 0;
                            _elment.GcdType = 0;
                            _elment.FStatus = '';
                            _elment.Unit_Weight = temp_allsetting ? temp_allsetting.STYLE : 1;
                            _elment.KDAUF = item.KDAUF;
                            _elment.KDPOS = item.KDPOS;
                            _elment.CustomerKey = item.CustomerKey;
                            view.refresh();
                            theGrid.endUpdate();
                        } else {
                            var newItem = view.addNew();
                            newItem.Resource_ID = item.Resource_ID;
                            newItem.Resource_index = item.Resource_index;
                            newItem.ParentID = item.WIP_ID;
                            newItem.Date = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                            newItem.Inventory_ID = item.Inventory_id;
                            newItem.Description = GdItem.Summary1; //temp_allsetting.length > 0 ? temp_allsetting[0].Description : '';
                            newItem.Number = item.IssuleNo;
                            newItem.BatchNO = item.BatchNO;
                            newItem.PlanQty = item.IssueQty;
                            newItem.Nbatch = item.Nbatch;
                            newItem.BzNbatch = 0;
                            newItem.IsBz = 0;
                            newItem.Lock = 0;
                            newItem.SaOrderKey = item.SaOrderKey;
                            newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.PbeginDate, 'yyyy/MM/dd');
                            newItem.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.PEndDate, 'yyyy/MM/dd');
                            newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.ScheduleStartDate, 'yyyy/MM/dd');
                            newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                            newItem.PlanDate = item.MfgPlanTime;
                            newItem.PlanNpkg = item.PlanNpkg;
                            newItem.StdInventory_ID = item.StdInventory_ID;
                            newItem.MfgCatID = item.MfgCatID;
                            newItem.HCapacity = item.HCapacity;
                            newItem.Summary = item.Summary;
                            newItem.Matching = item.Matching;
                            newItem.SaOrderKey = item.SaOrderKey ? item.SaOrderKey : 0;
                            newItem.ScheduleDateDifference = 0;
                            newItem.GcdType = 0;
                            newItem.FStatus = '';
                            newItem.Unit_Weight = temp_allsetting ? temp_allsetting.STYLE : 1;
                            newItem.KDAUF = item.KDAUF;       // LAB31211007
                            newItem.KDPOS = item.KDPOS;       // LAB31211007
                            newItem.CustomerKey = item.CustomerKey;       // LAB31211007								
                            view.commitNew();
                        }
                    }
                });
                theGrid.collectionView.refresh();
                theGrid.collapseGroupsToLevel(3);
                AssessAddSpRows(theGrid.itemsSource.items);
                IsInit = false;
            } else {
                Alert('提示:', '只能选择一条数据！');
            }
        }
    });
}
/**
 * 读取原计划
 * 读取当天以前的排产计划到当前排产界面
 * 
 * */
let ReadOldPlan = function () {
    var source = theGrid.itemsSource.sourceCollection;
    var WorkShopLineMapData_Tmp = new Array();
    getTopWindow().openWindow("原排产计划", "/ProductionPlanGcd?disble_operate_type=Add,Edit,Delete,Print,Record,BackRecord,Verify,Search&selectmode=true&Maker=" + getTopWindow().username + "&MakeDate<" + now, 900, 600, function (v) {
        if (v != null && typeof (v) == "object") {
            if (v.length == 2) {
                source.splice(0, source.length);
                var child_list = getListWithMultParams("ProductionPlanGcdDetail", { ProductionNo: v[1].ProductionNo });
                child_list.sort(function (a, b) { return a.Noid - b.Noid });
                theGrid.collectionView.refresh();
                let ccArry = {};
                var view = theGrid.collectionView;
                if (child_list.length == 0) {
                    return;
                }
                var WorkShopLineMapData = new Array();
                foreach(WorkShopLineMapData_Tmp, function (it) {
                    WorkShopLineMapData.push(it);
                })
                theGrid.RefreshColumnDataMap(WorkShopLineMapData);
                foreach(child_list, function (item) {
                    var GdItem = getItem('Material_Issue_Plan', 'NO', item.IssuleNo);
                    let nowDate = new Date().format('yyyy/MM/dd');
                    if (item.IssuleNo || item.IssuleNo.indexOf("XGCD") == 0 || item.IssuleNo.indexOf("T") == 0) {
                        let ScheduleEndDate = new Date(item.ScheduleEndDate).format('yyyy/MM/dd');
                        if (ScheduleEndDate >= nowDate) {
                            let temp_allsetting = AllSettings.find(x => x.Inventory_ID == item.Inventory_id);
                            if (ccArry[item.Resource_ID + ScheduleEndDate] == null) {
                                ccArry[item.Resource_ID + ScheduleEndDate] = 1;
                                let temp = WorkShopLine.find(x => x.Code_ID == item.Resource_ID);
                                if (temp) {
                                    for (let index = 0; index < temp.Nbatch; index++) {
                                        addSpRows({
                                            ParentID: item.WIP_ID,
                                            Date: ScheduleEndDate,
                                            Resource_index: item.Resource_index,
                                            Resource_ID: item.Resource_ID
                                        }, view);
                                    }
                                }
                            }
                            let __n = SpRows(source, ScheduleEndDate, item.Resource_ID);
                            if (IsNumber(__n)) {
                                let _elment = source[__n];
                                theGrid.beginUpdate();
                                _elment.Resource_ID = item.Resource_ID;
                                _elment.Resource_index = item.Resource_index;
                                _elment.ParentID = item.WIP_ID;
                                _elment.Date = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                                _elment.Inventory_ID = item.Inventory_id;
                                _elment.Description = GdItem.Summary1;//temp_allsetting.length > 0 ? temp_allsetting[0].Description : '';
                                _elment.Number = item.IssuleNo;
                                _elment.BatchNO = item.BatchNO;
                                _elment.PlanQty = item.IssueQty;
                                _elment.Nbatch = item.Nbatch;
                                _elment.BzNbatch = item.BzNbatch;
                                _elment.IsBz = item.BzNbatch;
                                _elment.Lock = 0;
                                _elment.SaOrderKey = item.SaOrderKey;
                                _elment.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.PbeginDate, 'yyyy/MM/dd');
                                _elment.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.PEndDate, 'yyyy/MM/dd');
                                _elment.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.ScheduleStartDate, 'yyyy/MM/dd');
                                _elment.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                                _elment.PlanDate = item.MfgPlanTime;
                                _elment.PlanNpkg = item.PlanNpkg;
                                _elment.StdInventory_ID = item.StdInventory_ID;
                                _elment.MfgCatID = item.MfgCatID;
                                _elment.HCapacity = item.HCapacity;
                                _elment.Summary = item.Summary;
                                _elment.Matching = item.Matching;
                                _elment.SaOrderKey = item.SaOrderKey ? item.SaOrderKey : 0;
                                _elment.ScheduleDateDifference = 0;
                                _elment.GcdType = 0;
                                _elment.FStatus = '';
                                _elment.Unit_Weight = temp_allsetting ? temp_allsetting.STYLE : 1;
                                _elment.KDAUF = item.KDAUF;       // LAB31211007
                                _elment.KDPOS = item.KDPOS;       // LAB31211007
                                _elment.CustomerKey = item.CustomerKey;       // LAB31211007
                                view.refresh();
                                theGrid.endUpdate();
                            } else {
                                var newItem = view.addNew();
                                newItem.Resource_ID = item.Resource_ID;
                                newItem.Resource_index = item.Resource_index;
                                newItem.ParentID = item.WIP_ID;
                                newItem.Date = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                                newItem.Inventory_ID = item.Inventory_id;
                                newItem.Description = GdItem.Summary1;// temp_allsetting.length > 0 ? temp_allsetting[0].Description : '';
                                newItem.Number = item.IssuleNo;
                                newItem.BatchNO = item.BatchNO;
                                newItem.PlanQty = item.IssueQty;
                                newItem.Nbatch = item.Nbatch;
                                newItem.BzNbatch = 0;
                                newItem.IsBz = 0;
                                newItem.Lock = 0;
                                newItem.SaOrderKey = item.SaOrderKey;
                                newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.PbeginDate, 'yyyy/MM/dd');
                                newItem.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.PEndDate, 'yyyy/MM/dd');
                                newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.ScheduleStartDate, 'yyyy/MM/dd');
                                newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                                newItem.PlanDate = item.MfgPlanTime;
                                newItem.PlanNpkg = item.PlanNpkg;
                                newItem.StdInventory_ID = item.StdInventory_ID;
                                newItem.MfgCatID = item.MfgCatID;
                                newItem.HCapacity = item.HCapacity;
                                newItem.Summary = item.Summary;
                                newItem.Matching = item.Matching;
                                newItem.SaOrderKey = item.SaOrderKey ? item.SaOrderKey : 0;
                                newItem.ScheduleDateDifference = 0;
                                newItem.GcdType = 0;
                                newItem.FStatus = '';
                                newItem.Unit_Weight = temp_allsetting ? temp_allsetting.STYLE : 1;
                                newItem.KDAUF = item.KDAUF;       // LAB31211007
                                newItem.KDPOS = item.KDPOS;       // LAB31211007
                                newItem.CustomerKey = item.CustomerKey;       // LAB31211007								
                                view.commitNew();
                            }
                        }
                    }
                });
                theGrid.collapseGroupsToLevel(3);
                AssessAddSpRows(theGrid.itemsSource.items);
                IsInit = false;
            } else {
                Alert('提示:', '只能选择一条数据！');
            }
        }
    });
}
/***
     * 下移
     * 将选中的行记录向下移动一行
     * */
let MoveDown = function (downbtn) {
    let source = theGrid.itemsSource.items;

    if (theGrid.selectedItems.length < 1) {
        Alert('提示：', '请选择操作项');
        return false;
    } else {
        downbtn.disable();
        let cv = theGrid.collectionView;
        let rows = theGrid.selectedItems[0];
        let item_index = rows.index;
        let new_item_index = item_index + 1
        if (item_index < source.length) {
            if (new_item_index < source.length) {
                theGrid.beginUpdate();
                let item = source[item_index];
                let newitem = source[new_item_index];
                let gcd_type = item.GcdType;

                let old_id = item.index;
                let new_id = newitem.index;

                let old_date = item.Date;
                let new_date = newitem.Date;

                let old_scheduleenddate = item.ScheduleEndDate;
                let new_scheduleenddate = newitem.ScheduleEndDate;

                if (gcd_type == 4 || item.Lock == 1) {
                    if (new Date(old_date) - new Date(new_date) == 0) {

                        item.index = new_id;
                        newitem.index = old_id;

                        item.Date = new_date;
                        newitem.Date = old_date;

                        item.ScheduleEndDate = new_scheduleenddate;
                        newitem.ScheduleEndDate = old_scheduleenddate;
                    } else {
                        alert('不能移除固定范围！');
                    }
                } else {

                    item.index = new_id;
                    newitem.index = old_id;

                    item.Date = new_date;
                    newitem.Date = old_date;

                    item.ScheduleEndDate = new_scheduleenddate;
                    newitem.ScheduleEndDate = old_scheduleenddate;
                }
                cv.refresh();
                theGrid.endUpdate();
            }
        }
    }
}
/***
* 上移
* 将选择的行记录向上移动一行
* */
let MoveUpward = function (upbtn, e) {
    let source = theGrid.itemsSource.items;
    if (theGrid.selectedItems.length < 1) {
        Alert('提示：', '请选择操作项');
        return false;
    } else {
        upbtn.disable();
        let cv = theGrid.collectionView;
        let rows = theGrid.selectedItems[0];
        let item_index = rows.index;
        let new_item_index = item_index - 1

        if (item_index > 0) {
            if (new_item_index >= 0) {
                theGrid.beginUpdate();
                let item = source[item_index];
                let newitem = source[new_item_index];
                let gcd_type = item.GcdType;

                let old_id = item.index;
                let new_id = newitem.index;

                let old_date = item.Date;
                let new_date = newitem.Date;

                let old_scheduleenddate = item.ScheduleEndDate;
                let new_scheduleenddate = newitem.ScheduleEndDate;

                if (gcd_type == 4 || item.Lock == 1) {
                    if (new Date(old_date) - new Date(new_date) == 0) {

                        item.index = new_id;
                        newitem.index = old_id;

                        item.Date = new_date;
                        newitem.Date = old_date;

                        item.ScheduleEndDate = new_scheduleenddate;
                        newitem.ScheduleEndDate = old_scheduleenddate;
                    } else {
                        alert('不能移除固定范围！');
                    }
                } else {

                    item.index = new_id;
                    newitem.index = old_id;

                    item.Date = new_date;
                    newitem.Date = old_date;

                    item.ScheduleEndDate = new_scheduleenddate;
                    newitem.ScheduleEndDate = old_scheduleenddate;
                }
                cv.refresh();
                theGrid.endUpdate();
            }
        }
    }
}
/**
 * 查看指定工单缺料
 * 根据选择的工去sap的接口查询缺少的物料
 **/
let ViewGdItemShortage = function () {
    var Garray = [];
    let cv = theGrid.itemsSource;
    let bcplist = new Array();
    if (cv.currentItem == null || cv.currentItem == '' || cv.currentItem == undefined) {
        Alert('提示：', '请选择需要查询的物料！');
        return false;
    } else {
        //Garray.push({
        //AUFNR: cv.currentItem.Number
        //});
        var cond = {
            t: "and", child: [{ c: "BatchNO", cp: '=', v: cv.currentItem.BatchNO }]
        }
        bcplist = getListWithMultParams("Material_Issue_Plan", { _cdt: jsonEncode(cond) });
        if (bcplist.length > 0) {
            for (let index = 0; index < bcplist.length; index++) {
                const element = bcplist[index];
                Garray.push({ AUFNR: element.NO });
            }
        }
    }
    var arg = {
        url: 'http://sapr3pci01.nipponpaint.com.cn:8000/sap/bc/srt/wsdl/flv_10002A111AD1/bndg_url/sap/bc/srt/rfc/sap/zws_ecc_p9_aps_03/500/zws_ecc_p9_aps_03/binding?sap-client=500',
        username: 'APSLOGON',
        password: 'initinit',
        method: 'ZPP_ECC_P9_APS_03',
        classname: 'zws_ecc_p9_aps_03',
        argument: {
            "0": jsonEncode({
                ET_PRODRET: [],
                IT_AUFNR: Garray,
                ET_SHORTMAT: []
            })
        }
    };
    Wait.Start(null, "数据同步中........");
    var ret = callWebService(arg, true, (ret) => {
        Wait.hide();
        if (!ret[0].success) {
            alert(ret[0].message);
            return;
        }
        var retobj = jsonDecode(ret[1]);
        var st_data = [];
        foreach(retobj.ET_SHORTMAT, function (ve) {
            var obj = new Object();
            obj.AUFNR = ve.AUFNR;
            obj.MATNR = ve.MATNR;
            obj.MAKTX = ve.MAKTX;
            obj.BDMNG = ve.BDMNG;
            obj.QL_QTY = ve.QL_QTY;
            obj.MEINS = ve.MEINS;
            obj.IS_INTRANSIT = ve.IS_INTRANSIT;
            var gd_ary = bcplist.find(x => x.NO == ve.AUFNR);
            obj.Type = gd_ary ? gd_ary.Type : -1;
            if (obj.Type == 1 || obj.Type == 2) {
                st_data.push(obj);
            }
        });

        var grid = Ext.create('Ext.grid.Panel', {
            store: Ext.create('Ext.data.Store', {
                fields: ['AUFNR', 'MATNR', 'MAKTX', 'BDMNG', 'QL_QTY', 'MEINS', 'IS_INTRANSIT', 'Type'],
                data: st_data
            }),
            height: 400,
            stripeRows: true,
            viewConfig: { forceFit: true },
            plugins: {
                gridfilters: true
            },
            columns: [
                { header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
                { header: 'SAP生产单号', dataIndex: 'AUFNR', width: 117, align: 'center', sortable: false, menuDisabled: true },
                { header: '组件物料编码', dataIndex: 'MATNR', width: 100, align: 'center', sortable: false, menuDisabled: true },
                { header: '组件描述', dataIndex: 'MAKTX', width: 330, align: 'center', sortable: false, menuDisabled: true },
                { header: '组件数量', dataIndex: 'BDMNG', width: 73, align: 'center', sortable: false, menuDisabled: true },
                { header: '缺料数量', dataIndex: 'QL_QTY', width: 73, align: 'center', sortable: false, menuDisabled: true },
                { header: '单位', dataIndex: 'MEINS', width: 47, align: 'center', sortable: false, menuDisabled: true },
                {
                    header: '是否在途满足', dataIndex: 'IS_INTRANSIT', width: 100, align: 'center', sortable: false, menuDisabled: true,
                    renderer: function (val) {
                        return val == 'Y' ? '是' : '否';
                    }
                },
                {
                    header: '工单类型', dataIndex: 'Type', width: 100, align: 'center', sortable: false, menuDisabled: true,
                    // filter: {
                    //     type: 'string', itemDefaults: { emptyText: '查询...' }, value: '1'
                    // },
                    renderer: function (val) {
                        if (val == 1) {
                            return '成品工单'
                        }
                        if (val == 0) {
                            return '半成品工单'
                        }
                        if (val == -1) {
                            return '无工单信息'
                        }
                    }
                }
            ]
        });
        var init_wind = Ext.create('Ext.window.Window', {
            title: cv.currentItem.Number + ':短缺物料',
            width: 1020,
            height: 480,
            modal: true,
            items: [grid],
            listeners: {
                resize: function (wn, width, height, eOpts) {
                    let grid = wn.items.items[0];
                    grid.setHeight(height - 80);
                    grid.setWidth(width - 15);
                }
            }, fbar: [{
                type: 'button',
                text: '确定',
                handler: function () { init_wind.close(); }
            }]
        });
        init_wind.show();
    });
}
/***
 * 工单缺料明细
 * 将界面中的工单号传入sap的接口查询出工单的缺料明细
*/
let ViewGdListShortage = function () {
    var Garray = [];
    var source = theGrid.itemsSource.items;
    let bcppc = [];
    Wait.Start(null, "数据同步中........");
    foreach(source, function (item) {
        if (item.Number) {
            if (item.Matching == 0 || item.Matching == 2) {
                // Garray.push({
                //     AUFNR: item.Number
                // });
                bcppc.push(item.BatchNO);
            }
        }
    });
    var cond = {
        t: "and", child: [{ c: "BatchNO", cp: 'in', v: bcppc.join(';') }]
    }
    let bcplist = getListWithMultParams("Material_Issue_Plan", { _cdt: jsonEncode(cond) });
    if (bcplist.length > 0) {
        for (let index = 0; index < bcplist.length; index++) {
            const element = bcplist[index];
            Garray.push({ AUFNR: element.NO });
        }
    }
    var arg = {
        url: 'http://sapr3pci01.nipponpaint.com.cn:8000/sap/bc/srt/wsdl/flv_10002A111AD1/bndg_url/sap/bc/srt/rfc/sap/zws_ecc_p9_aps_03/500/zws_ecc_p9_aps_03/binding?sap-client=500',
        username: 'APSLOGON',
        password: 'initinit',
        method: 'ZPP_ECC_P9_APS_03',
        classname: 'zws_ecc_p9_aps_03',
        argument: {
            "0": jsonEncode({
                ET_PRODRET: [],
                IT_AUFNR: Garray,
                ET_SHORTMAT: []
            })
        }
    };
    var st_data = [];
    callWebService(arg, true, (ret) => {
        Wait.hide();
        if (!ret[0].success) {
            alert(ret[0].message);
            return;
        }
        var retobj = jsonDecode(ret[1]);

        foreach(retobj.ET_SHORTMAT, function (ve) {
            var obj = new Object();
            obj.AUFNR = ve.AUFNR;
            obj.MATNR = ve.MATNR;
            obj.MAKTX = ve.MAKTX;
            obj.BDMNG = ve.BDMNG;
            obj.QL_QTY = ve.QL_QTY;
            obj.MEINS = ve.MEINS;
            obj.IS_INTRANSIT = ve.IS_INTRANSIT;
            var gd_ary = bcplist.find(x => x.NO == ve.AUFNR);
            obj.Type = gd_ary ? gd_ary.Type : -1;
            if (obj.Type == 1 || obj.Type == 2) {
                st_data.push(obj);
            }
        });
        var store = Ext.create('Ext.data.Store', {
            fields: ['AUFNR', 'MATNR', 'MAKTX', 'BDMNG', 'QL_QTY', 'MEINS', 'IS_INTRANSIT', 'Type'],
            data: st_data
        });
        var grid = Ext.create('Ext.grid.Panel', {
            store: store,
            height: 400,
            stripeRows: true,
            viewConfig: {
                forceFit: true
            },
            plugins: {
                gridfilters: true
            },
            columns: [
                { header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
                { header: 'SAP生产单号', dataIndex: 'AUFNR', width: 117, align: 'center', sortable: false, menuDisabled: true },
                { header: '组件物料编码', dataIndex: 'MATNR', width: 100, align: 'center', sortable: false, menuDisabled: true },
                { header: '组件描述', dataIndex: 'MAKTX', width: 330, align: 'center', sortable: false, menuDisabled: true },
                { header: '组件数量', dataIndex: 'BDMNG', width: 73, align: 'center', sortable: false, menuDisabled: true },
                { header: '缺料数量', dataIndex: 'QL_QTY', width: 73, align: 'center', sortable: false, menuDisabled: true },
                { header: '单位', dataIndex: 'MEINS', width: 47, align: 'center', sortable: false, menuDisabled: true },
                {
                    header: '是否在途满足', dataIndex: 'IS_INTRANSIT', width: 100, align: 'center', sortable: false, menuDisabled: true,
                    renderer: function (val) {
                        return val == 'Y' ? '是' : '否';
                    }
                },
                {
                    header: '工单类型', dataIndex: 'Type', width: 100, align: 'center', sortable: false, menuDisabled: true,
                    // filter: {
                    //     type: 'string', itemDefaults: { emptyText: '查询...' }, value: '1'
                    // },
                    renderer: function (val) {
                        if (val == 1) {
                            return '成品工单'
                        }
                        if (val == 0) {
                            return '半成品工单'
                        }
                        if (val == 2) {
                            return '一体板工单'
                        }
                        if (val == -1) {
                            return '无工单信息'
                        }
                    }
                }
            ],
            tbar: [
                {
                    text: '导出Excel',
                    glyph: 0xf1c3,
                    handler: function () {
                        grid2Excel(grid, "工单缺料明细");
                    }
                }
            ]
        });
        var init_wind = Ext.create('Ext.window.Window', {
            title: '短缺物料',
            width: 1020,
            height: 480,
            modal: true,
            maximizable: true,
            items: [grid],
            listeners: {
                resize: function (wn, width, height, eOpts) {
                    let grid = wn.items.items[0];
                    grid.setHeight(height - 80);
                    grid.setWidth(width - 15);
                },
                show: function () {
                    Wait.hide();
                    grid.getStore()
                }
            },
            fbar: [
                {
                    type: 'button',
                    text: '确定',
                    handler: function () {
                        init_wind.close();
                    }
                }
            ]
        });
        init_wind.show();
    });
}

/*
*按齐套日期排序
*ztext1
*/
let CompleteStore = Ext.create('Ext.data.Store', {
    fields: ['Resource_ID', 'Date', 'Number', 'Matching', 'MatchingDate', 'SortDate', 'Inventory_ID', 'STYLE', 'CQty', 'PlanNpkg'],
    data: [],
    groupField: 'Resource_ID',
    sorters: ['SortDate']
});
function CompleteDateSorting() {

    let resourceStore = Ext.create('Ext.data.Store', {
        fields: ['value', 'text'],
        data: []
    });
    let resourceCombox = Ext.create('Ext.form.ComboBox', {
        store: resourceStore,
        queryMode: 'local',
        displayField: 'text',
        valueField: 'value',
        editable: false
    });
    let dateField = { xtype: 'datefield', anchor: '100%', format: "Y/m/d", value: new Date() }

    let res_ary = theGrid.getColumn('Resource_ID').dataMap.collectionView.items;

    foreach(res_ary, (item) => {
        resourceStore.addSorted({
            value: item.id,
            text: item.name
        });
    });
    let CompleteDateGrid = getTop().Ext.create('Ext.grid.Panel', {
        store: CompleteStore,
        region: 'center',
        features: [{ ftype: 'grouping' }],
        frame: false,
        viewConfig: {
            columnLines: true,
            stripeRows: true,
            enableTextSelection: true,
            animateShadow: true,
            forceFit: true
        },
        selModel: {
            mode: 'MULTI',
            checkboxSelect: true,
            injectCheckbox: 1,
            type: 'checkboxmodel'
        },
        plugins: {
            ptype: 'cellediting',
            clicksToEdit: 1
        },
        columns: [
            {
                header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true
            },
            {
                dataIndex: 'Resource_ID', header: '设备大类', width: 80, sortable: false, menuDisabled: true,
                renderer: rendererCombobox(resourceCombox)
            },
            {
                dataIndex: 'Date', header: '日期', width: 120, sortable: false, menuDisabled: true,
                completeOnEnter: false, renderer: function (value) {
                    return value.format('yyyy/MM/dd');
                }
            },
            {
                dataIndex: 'Number', header: '生产订单', width: 125, sortable: false, menuDisabled: true
            },
            {
                dataIndex: 'Matching', header: '齐套', width: 50, sortable: false, menuDisabled: true, renderer: function (value) {
                    return value == 1 ? '是' : '否';
                }
            },
            {
                dataIndex: 'MatchingDate', header: '齐套日期', width: 120, sortable: false, menuDisabled: true,
                completeOnEnter: false, renderer: function (value) {
                    return !value ? "" : new Date(value).format('yyyy/MM/dd');
                }
            },
            {
                dataIndex: 'SortDate', header: '排序日期', xtype: 'datecolumn', format: 'Y-m-d', width: 120, sortable: false, menuDisabled: true,
                completeOnEnter: false, field: dateField
            },
            {
                dataIndex: 'Inventory_ID', header: '产品', width: 150, sortable: false, menuDisabled: true
            },
            {
                dataIndex: 'Unit_Weight', header: '规格', width: 50, sortable: false, menuDisabled: true
            },
            {
                dataIndex: 'PlanNpkg', header: '桶数', width: 50, sortable: false, menuDisabled: true
            },
            {
                dataIndex: 'PlanQty', header: '总量', width: 70, sortable: false, menuDisabled: true
            }
        ]
    });
    var init_wind = Ext.create('Ext.window.Window', {
        title: '齐套日期排序预演',
        width: 1000,
        height: 600,
        layout: 'border',
        items: [CompleteDateGrid],
        tbar: [
            {
                type: 'button',
                text: '齐套日期排序',
                glyph: 0xf338,
                handler: function () {
                    let source = theGrid.itemsSource.items;
                    CompletSorting(source);
                    CompleteStore.sort('排序日期', 'ASC');
                }
            }, {
                type: 'button',
                text: '读取数据',
                glyph: 0xf019,
                handler: function (btn) {
                    Read('数据读取...', function (p, task) {
                        let source = theGrid.itemsSource.items;
                        CompleteStore.removeAll();

                        for (let index = 0; index < source.length; index++) {
                            const element = source[index];
                            if (element.Number && element.Number.indexOf("XGCD") != 0
                                && element.Number.indexOf("T") != 0
                                && element.Lock == 0
                            ) {
                                CompleteStore.add({
                                    Resource_ID: element.Resource_ID,
                                    Date: element.Date,
                                    Number: element.Number,
                                    Matching: element.Matching,
                                    MatchingDate: element.MatchingDate ? element.MatchingDate : '',
                                    SortDate: '',
                                    Inventory_ID: element.Inventory_ID,
                                    Unit_Weight: element.Unit_Weight,
                                    PlanQty: element.PlanQty,
                                    PlanNpkg: element.PlanNpkg
                                });
                            }
                            if (index == source.length - 1) {
                                p.hide();
                                task.stopAll();
                                ShowToast('数据读取完成!');
                            }
                        }
                    });
                }
            }
        ],
        fbar: [
            {
                type: 'button',
                text: '更新',
                glyph: 0xf0c7,
                handler: function () {
                    Confirm('提示：', '确定更新数据？', function () {
                        let source = theGrid.itemsSource.items;
                        for (let index = 0; index < source.length; index++) {
                            const element = source[index];
                            if (element.Number) {
                                let record = CompleteStore.findRecord('Number', element.Number);
                                if (record) {
                                    element.Date = record.get('SortDate');
                                    element.ScheduleStartDate = record.get('SortDate');
                                    element.ScheduleEndDate = record.get('SortDate');
                                }
                            }
                        }
                        theGrid.collectionView.refresh();
                        ShowToast("数据更新完成！");
                        return false;
                    }, null, null);
                }
            },
            {
                type: 'button',
                text: '取消',
                glyph: 0xf410,
                handler: function () {
                    init_wind.close();
                }
            }
        ]
    });
    init_wind.show();
}
function CompletSorting() {
    let store = CompleteStore.getData();
    let NotQt = [];   //不齐套、在途
    let Qt = [];   //齐套
    let FnQt = [];   //完工

    store.each(function (record) {
        //条件符合不齐套  Matching==0 
        if (record.get('Matching') == 0) {
            NotQt.push(record.getData())
        }
        //条件符合齐套  Matching==1
        if (record.get('Matching') == 1) {
            Qt.push(record.getData())
        }
        //条件符合齐套（在途）  Matching==2
        if (record.get('Matching') == 2) {
            NotQt.push(record.getData())
        }
        //条件符合完工   Matching==3
        if (record.get('Matching') == 3) {
            FnQt.push(record.getData());
        }
    });
    //处理完工工单数据
    for (let index = 0; index < FnQt.length; index++) {
        const element = FnQt[index];
        element.SortDate = element.Date
    }
    //处理齐套工单数据
    for (let index = 0; index < Qt.length; index++) {
        const element = Qt[index];
        element.SortDate = element.Date
    }
    //处理不齐套、在途工单数据
    NotQt = NotQt.sort(function (a, b) { return a.MatchingDate > b.MatchingDate ? 1 : -1; })

    for (let index = 0; index < NotQt.length; index++) {
        const element = NotQt[index];
        element.SortDate = element.Date
        if (new Date(element.MatchingDate).format('yyyy') == "2999") {
            NotQt[index].SortDate = element.MatchingDate;
        } else {
            if (element.MatchingDate) {
                NotQt[index].SortDate = addDate(element.MatchingDate, 1)
            } else {
                NotQt[index].SortDate = addDate(element.Date, 1)
            }

        }
    }

    let Res_Arry = FnQt.concat(Qt, NotQt);
    for (let index = 0; index < Res_Arry.length; index++) {
        const element = Res_Arry[index];
        let record = CompleteStore.findRecord('Number', element.Number);
        if (record) {
            if (element.SortDate) {
                record.set('SortDate', new Date(element.SortDate));
            } else {
                record.set('SortDate', null);
            }
        }
    }
    ShowToast("计算完成！");
}
function Read(msg, call) {
    var progressBar = Ext.MessageBox.show({
        msg: msg,
        progressText: msg,
        width: 300,
        wait: { interval: 200 }
    });
    var task1 = new Ext.util.TaskRunner();
    task1.start({
        run: function () {
            call(progressBar, task1);
        },
        interval: 1000
    })
}